Help!  Simple Java Program.

Here is the problem: Write a program that creates a loan amortization table. The user of the program will supply values for Initial Loan Principal, Annual Percentage Rate and Monthly Payment. The program should print out the appropriate amortization table including the number of Monthly Payments and the Total Interest paid for the life of the loan. The program should allow multiple
runs (up to 4 different versions) of the table process and should allow the
user to compare runs in a tabular format.
This is what I have so far and should work one I completely debug it. I am really new to Java, and I thinks it is somthing to do with the Array. I recently switched from C++ to Java, so I don't think I have the syntax down correctly. Thanks.
import javax.swing.JOptionPane;
public class Program_01
     public static void main(String [] args)
          int Runs;
          do{
                    String Run_Question = JOptionPane.showInputDialog(null, "How many times,would you like to run" + 
                    " the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
                     Runs = Integer.parseInt(Run_Question);
                    if( Runs < 0 || Runs > 4)
                         JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
                         JOptionPane.INFORMATION_MESSAGE);
               }while(Runs < 0 || Runs > 4);
               Questions(Runs);
     public static void Questions(int Runs)
          for(int index = 0;index < Runs;index ++)
               String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
                                                     JOptionPane.QUESTION_MESSAGE);     
               String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
                                                       "Interest Rate", JOptionPane.QUESTION_MESSAGE);
               String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
                                                       JOptionPane.QUESTION_MESSAGE);
               double Loan_Principle = Double.parseDouble(Loan_Principle_String);
               double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
               double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
               Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);
     public static void Calculate (double Loan, double Percentage, double Monthly)
          double[] Principle = new double[]{0,0};
          double[] Interest = new double[]{0,0};
          double[] Remain = new double[]{0,0};
          double Monthly_Percent = Percentage/12;
          double MPR = ((int)((Monthly_Percent + .005) * 100.) / 100.);
          boolean Over = true;          
          double Borrowed = Loan;          
          int Month = 0;
          for (int index = 0; Over != false; index++)
               double Rate = MPR * Loan;
               double decimalRate = ((int)((Rate + .005) * 100.) / 100.);
               Interest[index] = decimalRate;
               double Prince = Monthly - decimalRate;
               double decimalPrince = ((int)((Prince + .005) * 100.) / 100.);
               Principle[index]= decimalPrince;
               double Rmn = Borrowed - decimalPrince;
               Borrowed = Rmn;
               double decimalRmn = ((int)((Rmn + .005) * 100.) / 100.);
               Remain[index] = decimalRmn;
               if(Monthly > Remain[index] && Remain[index] > 0)
                    Monthly = Remain[index];
                    Over = false;
               Month += 1;
          System.out.println("I am here!" + Month);
          System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "APR" + " " + "MPR" +
           " " + "Interest Payment" + " " + "Principle Payment");
          System.out.println("------------------------------------------------------------------------");
          for(int index = 0; index < Month; index++)
               System.out.println((index + 1) + "\t" + Remain[index] + "\t" + Percentage + "\t" + MPR + "\t" + Interest[index]
                + "\t" + Principle[index]);
}

Okay, here is my updated code. I am having trouble outputting my formate to align with each category.
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Program_01
     public static void main(String [] args)
          int Runs;
          do
               String Run_Question = JOptionPane.showInputDialog(null, "How many times would you like to run" + 
               " the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
                Runs = Integer.parseInt(Run_Question);
               if( Runs < 0 || Runs > 4)
                    JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
                    JOptionPane.INFORMATION_MESSAGE);
          }while(Runs < 0 || Runs > 4);
               Questions(Runs);
     public static void Questions(int Runs)
          for(int index = 0;index < Runs;index ++)
               String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
                                                     JOptionPane.QUESTION_MESSAGE);     
               String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
                                                       "Interest Rate", JOptionPane.QUESTION_MESSAGE);
               String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
                                                       JOptionPane.QUESTION_MESSAGE);
               double Loan_Principle = Double.parseDouble(Loan_Principle_String);
               double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
               double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
               Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);     
     public static void Calculate (double Loan, double Percentage, double Monthly)
          double[] Principle = new double[100];
          double[] Interest = new double[100];
          double[] Remain = new double[100];
          double[] Payment = new double[100];
          DecimalFormat Decimal = new DecimalFormat(".00");
          double Total_Interest = 0;
          double T_Interest;          
          double Monthly_Percent = (Percentage/12)/100;
          double MPR = Monthly_Percent;
          boolean Over = true;          
          double Borrowed = Loan;
          double Deposit = Monthly;          
          int Month = 0;
          for (int index = 0; Over = true; index++)
               double Rate = MPR * Borrowed;
               double decimalRate = round(Rate,2);
               Interest[index] = decimalRate;
               Remain[index] = Borrowed;
               Month += 1;     
               if(Monthly > Remain[index ] && Remain[index ] > 0)
                    for(int count = 0; count <= Month; count++)
                         Total_Interest += Interest[count];     
                    T_Interest = round(Total_Interest,2);
                    Payment[index] = T_Interest;
                    Deposit = T_Interest;     
               else
                    Payment[index] = Deposit;     
               double Prince = Deposit - decimalRate;
               double decimalPrince = round(Prince,3);
               Principle[index]= decimalPrince;
               System.out.println("I am here!" + decimalPrince);
               double Rmn = Borrowed - decimalPrince;
               double decimalRmn = round(Rmn,2);
               Borrowed = decimalRmn;
               if(Monthly > Remain[index ] && Remain[index ] > 0)
                    Over = false;
                    break;
          System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "Percentage" + " " + "MPR" +
           " " + "Interest Payment" + " " + "Principle Payment");
          System.out.println("----------------------------------------------------------------------------");
          for(int index = 0; index < Month; index++)
               System.out.println("   " + (index + 1) + "\t   " + Decimal.format(Remain[index]) + "   " +
               Decimal.format(Payment[index]) + "   " + Decimal.format(Percentage) + "     " + MPR +
               "\t" + Decimal.format(Interest[index]) + "\t\t" + Decimal.format(Principle[index]));     
          T_Interest = ((int)((Total_Interest + .005) * 100.) / 100.);
          System.out.println("\n\t\t\t" + "Total Interest Paid \t" + T_Interest + "\n");
          for(int index = 0; index < Month; index++)
               System.out.printf("%f %f\n", Principle[index],Remain[index]);
     public static double round(double val, int places) {
     long factor = (long)Math.pow(10,places);
     // Shift the decimal the correct number of places
     // to the right.
     val = val * factor;
     // Round to the nearest integer.
     long tmp = Math.round(val);
     // Shift the decimal the correct number of places
     // back to the left.
     return (double)tmp / factor;
}

Similar Messages

  • Problem while executing simple java program

    Hi
    while trying to execute a simple java program,i am getting the following exception...
    please help me in this
    java program :import java.util.*;
    import java.util.logging.*;
    public class Jump implements Runnable{
        Hashtable activeQueues = new Hashtable();
        String dbURL, dbuser, dbpasswd, loggerDir;   
        int idleSleep;
        static Logger logger = Logger.getAnonymousLogger();      
        Thread myThread = null;
        JumpQueueManager manager = null;
        private final static String VERSION = "2.92";
          public Jump(String jdbcURL, String user, String pwd, int idleSleep, String logDir) {
            dbURL = jdbcURL;
            dbuser = user;
            dbpasswd = pwd;
            this.idleSleep = idleSleep;
            manager = new JumpQueueManager(dbURL, dbuser, dbpasswd);
            loggerDir = logDir;
            //preparing logger
            prepareLogger();
          private void prepareLogger(){      
            Handler hndl = new pl.com.sony.utils.SimpleLoggerHandler();
            try{
                String logFilePattern = loggerDir + java.io.File.separator + "jumplog%g.log";
                Handler filehndl = new java.util.logging.FileHandler(logFilePattern, JumpConstants.MAX_LOG_SIZE, JumpConstants.MAX_LOG_FILE_NUM);
                filehndl.setEncoding("UTF-8");
                filehndl.setLevel(Level.INFO);
                logger.addHandler(filehndl);
            catch(Exception e){
            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);
            logger.addHandler(hndl);
            logger.setLevel(Level.FINE);
            logger.info("LOGGING FACILITY IS READY !");
          private void processTask(QueueTask task){
            JumpProcessor proc = JumpProcessorGenerator.getProcessor(task);       
            if(proc==null){
                logger.severe("Unknown task type: " + task.getType());           
                return;
            proc.setJumpThread(myThread);
            proc.setLogger(logger);       
            proc.setJumpRef(this);
            task.setProcStart(new java.util.Date());
            setExecution(task, true);       
            new Thread(proc).start();       
         private void processQueue(){       
            //Endles loop for processing tasks from queue       
            QueueTask task = null;
            while(true){
                    try{
                        //null argument means: take first free, no matters which queue
                        do{
                            task = manager.getTask(activeQueues);
                            if(task!=null)
                                processTask(task);               
                        while(task!=null);
                    catch(Exception e){
                        logger.severe(e.getMessage());
                logger.fine("-------->Sleeping for " + idleSleep + " minutes...hzzzzzz (Active queues:"+ activeQueues.size()+")");
                try{
                    if(!myThread.interrupted())
                        myThread.sleep(60*1000*idleSleep);
                catch(InterruptedException e){
                    logger.fine("-------->Wakeing up !!!");
            }//while       
        public void setMyThread(Thread t){
            myThread = t;
        /** This method is only used to start Jump as a separate thread this is
         *usefull to allow jump to access its own thread to sleep wait and synchronize
         *If you just start ProcessQueue from main method it is not possible to
         *use methods like Thread.sleep becouse object is not owner of current thread.
        public void run() {
            processQueue();
        /** This is just another facade to hide database access from another classes*/
        public void updateOraTaskStatus(QueueTask task, boolean success){
            try{         
                manager.updateOraTaskStatus(task, success);
            catch(Exception e){
                logger.severe("Cannot update status of task table for task:" + task.getID() +  "\nReason: " + e.getMessage());       
        /** This is facade to JumpQueueManager method with same name to hide
         *existance of database and SQLExceptions from processor classes
         *Processor class calls this method to execute stored proc and it doesn't
         *take care about any SQL related issues including exceptions
        public void executeStoredProc(String proc) throws Exception{
            try{
                manager.executeStoredProc(proc);
            catch(Exception e){
                //logger.severe("Cannot execute stored procedure:"+ proc + "\nReason: " + e.getMessage());       
                throw e;
         *This method is only to hide QueueManager object from access from JumpProcessors
         *It handles exceptions and datbase connecting/disconnecting and is called from
         *JumpProceesor thread.
        public  void updateTaskStatus(int taskID, int status){       
            try{
                manager.updateTaskStatus(taskID, status);
            catch(Exception e){
                logger.severe("Cannot update status of task: " + taskID + " to " + status + "\nReason: " + e.getMessage());
        public java.sql.Connection getDBConnection(){
            try{
                return manager.getNewConnection();
            catch(Exception e){
                logger.severe("Cannot acquire new database connection: " + e.getMessage());
                return null;
        protected synchronized void setExecution(QueueTask task, boolean active){
            if(active){
                activeQueues.put(new Integer(task.getQueueNum()), JumpConstants.TH_STAT_BUSY);
            else{
                activeQueues.remove(new Integer(task.getQueueNum()));
        public static void main(String[] args){
                 try{
             System.out.println("The length-->"+args.length);
            System.out.println("It's " + new java.util.Date() + " now, have a good time.");
            if(args.length<5){
                System.out.println("More parameters needed:");
                System.out.println("1 - JDBC strign, 2 - DB User, 3 - DB Password, 4 - sleeping time (minutes), 5 - log file dir");
                return;
            Jump jump = new Jump(args[0], args[1], args[2], Integer.parseInt(args[3]), args[4]);
            Thread t1= new Thread(jump);
            jump.setMyThread(t1);      
            t1.start();}
                 catch(Exception e){
                      e.printStackTrace();
    } The exception i am getting is
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe
    Exception in thread "main" ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
    JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820] Please help me.....
    Thanks in advance.....sathya

    I am not willing to wade through the code, but this portion makes me conjecture your using an Oracle connect string instead of a class name.
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe

  • Need help connecting java-program to Clarion-software/database

    I have made a simple java-program which monitors control-lines in a computers com-port. Now I need to pass this information to Clarion-based software.
    I am currently writing the changes in to a file from which the clarion software will read the changes, but is there any better way to do this?

    Check out these websites:
    - http://www.softvelocity.com
    - http://en.wikipedia.org/wiki/Clarion_programming_language
    The problems is actually the fact that i don't have access to this clarion-based software or it's APIs etc.
    Message was edited by:
    RDuck

  • A simple Java program to be compiled with ojc and executed with java.exe

    Hi ,
    This thread is relevant to Oracle Java Compiler (file ojc) and jave.exe file.
    I have written a simple java program which consists of two simple simple classes and using the JDev's 10.1.3.2 ojc and java files , i'm trying to execute it after the successful compilation....
    The problem is that trying to run it... the error :
    Exception in thread "main" java.lang.NoClassDefFoundError: EmployeeTest
    appears.
    How can i solve this problem...????
    The program is as follows:
    import java.util.*;
    import corejava.*;
    public class EmployeeTest
    {  public static void main(String[] args)
       {  Employee[] staff = new Employee[3];
          staff[0] = new Employee("Harry Hacker", 35000,
             new Day(1989,10,1));
          staff[1] = new Employee("Carl Cracker", 75000,
             new Day(1987,12,15));
          staff[2] = new Employee("Tony Tester", 38000,
             new Day(1990,3,15));
          int i;
          for (i = 0; i < 3; i++) staff.raiseSalary(5);
    for (i = 0; i < 3; i++) staff[i].print();
    class Employee
    {  public Employee(String n, double s, Day d)
    {  name = n;
    salary = s;
    hireDay = d;
    public void print()
    {  System.out.println(name + "...." + salary + "...."
    + hireYear());
    public void raiseSalary(double byPercent)
    {  salary *= 1 + byPercent / 100;
    public int hireYear()
    {  return hireDay.getYear();
    private String name;
    private double salary;
    private Day hireDay;
    For compilation... i use :
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdev\bin\ojc -classpath D:\E-Book\Java\Sun_Java_Book_I\Corejava EmployeeTest.java
    For execution , i issue the command:
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    NOTE:I tried to use the jdk of Oracle database v.2 but the error :
    Unable to initialize JVM appeared....
    Thanks , a lot
    Simon

    Hi,
    Thanks god....
    I found a solution without using Jdev.....
    C:\oracle_files\Java\Examples>SET CLASSPATH=.;D:\E-Book\Java\Sun_Java_Book_I\Corejava
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\javac EmployeeTest.java
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    What does Ant has to do with this?Sorry, under the Ant tree a classpath label is found....I'm very new to Java and JDev...
    You need to include the jar file that has the Day method in it inside project properties->libraries.I have not .jar file.. just some .java files under the corejava directory.... By the way , I have inserted the corejava directory to the project pressing the button Add Jar/Directory.... , but the problem insists..
    Thanks , a lot
    Simon

  • Help with a simple Java program

    I'm making a sort of very simple quiz program with Java. I've got everything working on the input/output side of things, and I'm looking to just fancy everything up a little bit. This program is extremely simple, and is just being run through the Windows command prompt. I was wondering how exactly to go about making it to where the quiz taker was forced to hit the enter key after answering the question and getting feedback. Right now, once the question is answered the next question is immediately asked, and it looks kind of tacky. Thanks in advance for your help.

    Hmm.. thats not quite what I was looking for, I don't think. Here's an example of my program.
    class P1 {
    public static void main(String args[]) {
    boolean Correct;
    char Selection;
    int number;
    Correct = false;
    System.out.println("Welcome to Trivia!\n");
    System.out.println("Who was the first UF to win the Heisman Trophy?\n");
    System.out.print("A) Danny Wuerffel\nB) Steve Spurrier\nC) Emmit Smith\n");
    Selection = UserInput.readChar();
    if(Selection == 'B' | Selection == 'b')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    System.out.println("(\nHit enter for the next question...");
    System.in.readLine();
    Correct = false;
    System.out.println("\nWhat year did UF win the NCAA Football National Championship?\n");
    number = UserInput.readInt();
    if(number == 1996)
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    Correct = false;
    System.out.println("\nWho is the President of the University of Florida?\n");
    System.out.println("A) Bernie Machen\nB) John Lombardi\nC) Stephen C. O'Connell\n");
    Selection = UserInput.readChar();
    if(Selection == 'A' | Selection == 'a')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    }

  • I did write a simple java program but it is not working please help me.....

    This is the program I wrote LineRect just to draw a line a rectangle etc...... Y it is not working How can i used the same program to run without using applet that is by using awt and swing.........Pls Help me.............
    import java.awt.*;
    import java.io.*;
    public class LineRect
    {public void paint(Graphics g)
         {g.drawLine(10,10, 50,50);
         g.drawRect(10, 60, 40,30);
         g.fillRect(60,10,30,80);
         g.drawRoundRect(10,100,80,50,10,10);
         g.fillRoundRect(20,110,60,30,5,5);
         g.drawLine(100,10,230,140);
         g.drawLine(100,140,230,10);
    <APPLET
    CODE =LineRect.class
    WIDTH=250
    HEIGHT=200>
    </APPLET>

    There are many significant errors here for instance you are using a class file as if it were an applet yet you do not subclass applet. Your code has no init method (if it is to be an applet). Your best bet is to go through the tutorials one step at a time. One thing to consider is to subclass a JPanel and draw on the jpanel overriding the paintComponent method. This can then be added to a JFrame or a JApplet's contentPane and would allow the same graphics in both. But again, please study the tutorials on all of this, otherwise you will be doing hit-or-miss programming, and that is no way to learn.
    Much luck!
    Addendum: Also, if you are just beginning in Java programming, I suggest you start with the basics and not with Swing / AWT / graphics programming. Otherwise you will just end up bruised and disappointed. You have to learn to walk before you can run.
    Edited by: Encephalopathic on Dec 26, 2007 5:09 AM

  • Help with Simple JAVA program

    I'm a complete novice with Java. I want to write a Java program to run on Windows 2000 servers to write a list of certain files in a directory into a *.txt file. I hope to add complexity once I have this basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.

    I'm a complete novice with Java. I want to write a
    Java program to run on Windows 2000 servers to write
    a list of certain files in a directory into a *.txt
    file. I hope to add complexity once I have this
    basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.
    You need to create a method and insert your if statement in there

  • *****Please Help Simple Java Corba Problem*****

    This is probably a really simple one but I am very cheased off about it.
    I run my applications on a Win XP pro OS, and when I go to type in nameserv it gives me the following error I hava downloaded and installed JDK 1.4.1. I also have the JRE, And jbuilder personal edition ver 8.....And J2RE 1.4.1
    C:\Documents and Settings\Ash>nameserv
    Exception in thread "main" java.lang.NoClassDefFoundError: java/util/HashSet
    at com.inprise.vbroker.orb.ORB.<init>(ORB.java:81)
    at org.omg.CORBA.ORB.create_impl(ORB.java)
    at org.omg.CORBA.ORB.init(ORB.java)
    at com.inprise.vbroker.naming.ExtFactory.main(ExtFactory.java:126)
    my classpath looks like this
    .;C:\VisualCafePDETrial\BIN\COMPONENTS\SYMBEANS.JAR;C:\VisualCafePDETrial\JAVA\LIB\CLASSES.ZIP;C:\VisualCafePDETrial\JAVA\LIB;C:\BES\bin;C:\j2sdk1.4.1\lib\tools.jar;.;
    and my path is
    C:\VisualCafePDETrial\BIN;C:\VisualCafePDETrial\JAVA\BIN;C:\BES\binC:\j2sdk1.4.1\lib\tools.jar;.;
    what on earth am I doing wrong ??
    Also when I goto compile any java program it comes up with the following
    C:\DOCprac\Prac5\bank_naming>vbmake
    Building the bank_agent example ...
    Exception in thread "main" java.lang.ClassCastException
    at com.visigenic.vbroker.tools.idl2java.main(idl2java.java:30)
    Symantec Java! JustInTime Compiler Version 3.00.021(i) for JDK 1.1.x (TRIAL VER)
    Copyright (C) 1996-98 Symantec Corporation
    compiling: Client.java
    Client.java:2: Package org.omg.CORBA not found in import.
    import org.omg.CORBA.*;
    ^
    Client.java:3: Package org.omg.CosNaming not found in import.
    import org.omg.CosNaming.*;
    ^
    2 errors
    Symantec Java! JustInTime Compiler Version 3.00.021(i) for JDK 1.1.x (TRIAL VER)
    Please help I am really desperate to sort this one out. Can you give me some detailed info on how I would do this.>>>Thanx in advance

    You have 2 sets of errors, at least.
    The first is : Exception in thread "main" java.lang.NoClassDefFoundError: java/util/HashSet which is that you have not imported the class for hashset.
    The second is that the import of the jars is probably wrong, hard to say without seeing code.

  • Please help with Java program

    Errors driving me crazy! although compiles fine
    I am working on a project for an online class - I am teaching myself really! My last assignment I cannot get to work. I had a friend who "knows" what he is doing help me. Well that didn't work out too well, my class is a beginner and he put stuff in that I never used yet. I am using Jgrasp and Eclipse. I really am trying but, there really is no teacher with this online class. I can't get questions answered in time and stuff goes past due. I am getting this error:
    Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader .java:55)
    at java.util.Scanner.<init>(Scanner.java:590)
    at ttest.main(ttest.java:54)
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    This is my code:
    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    The assignment is:
    Create a Java program to read in an unknown number of lines from a data file. You will need to create the data file. The contents of the file can be found at the bottom of this document. This file contains a football team's name, the number of games they have won, and the number of games they have lost.
    Your program should accomplish the following tasks:
    1. Process all data until it reaches the end-of-file. Calculate the win percentage for each team.
    2. Output to a file ("top.txt") a listing of all teams with a win percentage greater than .500. This file should contain the team name and the win percentage.
    3. Output to a file ("bottom.txt") a listing of all teams with a win percentage of .500 or lower. This file should contain the team name and the win percentage.
    4. Count and print to the screen the number of teams with a record greater then .500 and the number of teams with a record of .500 and below, each appropriately labeled.
    5. Output in a message box: the team with the highest win percentage and the team with the lowest win percentage, each appropriately labeled. If there is a tie for the highest win percentage or a tie for the lowest win percentage, you must output all of the teams.
    Dallas 5 2
    Philadelphia 4 3
    Washington 3 4
    NY_Giants 3 4
    Minnesota 6 1
    Green_Bay 3 4

    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    }

  • Help with Java programming project

    Hi,
    I need help in writing this Java program. The purpose of this program is to read a variable-length stream of 0, 1 characters from an input text file (call it input.txt) one character at a time, and generate the corresponding B8ZS output stream consisting of the +, - , and 0 characters (with appropriate substitutions) one-character-at-a-time into a text file (called output.txt).
    The program must use a class called AMIConverter with an object called AMI . Class AMIConverter must have a method called convert which converts an individual input character 0 or 1 into the appropriate character 0 or + or - of AMI.
    It first copy the line to file output.txt. Then read the line one character at a time and pass only valid characters (0 or 1) to AMI.convert, which assumes only valid characters. The first 1 in each new 'Example' should be converted to a +.
    This is what is read in, but this is just a test case.
    0101<1000
    1100a1000b00
    1201g101
    should now produce two lines of output for each 'Example', as shown below:
    This should be the output of the output.txt file
    Example 1
    in :0101<1000
    out:0+0-+000
    Example 2
    in :1100a1000b00
    out:+-00+00000
    Example 3
    in :1201g101
    out:+0-+0-
    To elaborate more, only 1 and 0 are passed to "convert" method. All others are ignored. 0 become 0 and 1 become either + or - and the first "1" in each new example should be a +.
    This is what I have so far. So far I am not able to get the "in" part, the characters (e.g. : 0101<1000 ) out to the output.txt file. I am only able to get the "out" part. And I also can't get it to display a + for the first "1" in each new examples.
    import java.io.*;
    public class AMIConverter
         public static void main (String [] args) throws IOException
              AMI ami = new AMI();
              try
                   int ch = ' ';
                   int lineNum = 1;
         int THE_CHAR_0 = '0';
         int THE_CHAR_1 = '1';
                   BufferedReader infile = new BufferedReader(new FileReader("input.txt"));
         PrintWriter outfile = new PrintWriter("output.txt");
         outfile.write("Example " + lineNum);//prints Example 1
         outfile.println();
         outfile.write("in :");
    outfile.println();
    outfile.write("out:");
         while ((ch = infile.read()) != -1)
         if (ch == '\r' || ch == '\n')
              lineNum++;
              outfile.println();
              outfile.println();
              outfile.write("Example " + lineNum);
              outfile.println();
              outfile.write("in :");
              outfile.println();
              outfile.write("out:");
         else
         if (ch == THE_CHAR_0)
              int output = ami.convert(ch);
              outfile.write(output);
         else     
         if (ch == THE_CHAR_1)
              int output = ami.convert(ch);
              outfile.write(output);          
    }//end while
         infile.close();
         outfile.close();
         }catch (IOException ex) {}
    }//main method
    }//class AMIConverter
    This is my AMI class
    import java.io.*;
    public class AMI
         int THE_CHAR_0 = '0';
    int THE_CHAR_1 = '1';
    int total = '+';
    int minus = '-';
    int count = 0;
    public int convert(int ch)
         try
              PrintWriter outfile = new PrintWriter("output.txt");
              if (ch == THE_CHAR_0)
         return ch;
         else
         if (ch == THE_CHAR_1)
         count++;
         if (count%2 == 1)
              ch = total;
              return (ch);
         else
                             ch = minus;     
                             return (ch);      
    }catch (FileNotFoundException e) {}      
         return ch;
    }//method convert
    }//class AMI
    Any help would be appreicated.
    Thanks!

    Hi,
    I need help in writing this Java program. The purpose of this program is to read a variable-length stream of 0, 1 characters from an input text file (call it input.txt) one character at a time, and generate the corresponding B8ZS output stream consisting of the +, - , and 0 characters (with appropriate substitutions) one-character-at-a-time into a text file (called output.txt).
    The program must use a class called AMIConverter with an object called AMI . Class AMIConverter must have a method called convert which converts an individual input character 0 or 1 into the appropriate character 0 or + or - of AMI.
    It first copy the line to file output.txt. Then read the line one character at a time and pass only valid characters (0 or 1) to AMI.convert, which assumes only valid characters. The first 1 in each new 'Example' should be converted to a +.
    This is what is read in, but this is just a test case.
    0101<1000
    1100a1000b00
    1201g101
    should now produce two lines of output for each 'Example', as shown below:
    This should be the output of the output.txt file
    Example 1
    in :0101<1000
    out:0+0-+000
    Example 2
    in :1100a1000b00
    out:+-00+00000
    Example 3
    in :1201g101
    out:+0-+0-
    To elaborate more, only 1 and 0 are passed to "convert" method. All others are ignored. 0 become 0 and 1 become either + or - and the first "1" in each new example should be a +.
    This is what I have so far. So far I am not able to get the "in" part, the characters (e.g. : 0101<1000 ) out to the output.txt file. I am only able to get the "out" part. And I also can't get it to display a + for the first "1" in each new examples.
    import java.io.*;
    public class AMIConverter
    public static void main (String [] args) throws IOException
    AMI ami = new AMI();
    try
    int ch = ' ';
    int lineNum = 1;
    int THE_CHAR_0 = '0';
    int THE_CHAR_1 = '1';
    BufferedReader infile = new BufferedReader(new FileReader("input.txt"));
    PrintWriter outfile = new PrintWriter("output.txt");
    outfile.write("Example " + lineNum);//prints Example 1
    outfile.println();
    outfile.write("in :");
    outfile.println();
    outfile.write("out:");
    while ((ch = infile.read()) != -1)
    if (ch == '\r' || ch == '\n')
    lineNum++;
    outfile.println();
    outfile.println();
    outfile.write("Example " + lineNum);
    outfile.println();
    outfile.write("in :");
    outfile.println();
    outfile.write("out:");
    else
    if (ch == THE_CHAR_0)
    int output = ami.convert(ch);
    outfile.write(output);
    else
    if (ch == THE_CHAR_1)
    int output = ami.convert(ch);
    outfile.write(output);
    }//end while
    infile.close();
    outfile.close();
    }catch (IOException ex) {}
    }//main method
    }//class AMIConverterThis is my AMI class
    import java.io.*;
    public class AMI
    int THE_CHAR_0 = '0';
    int THE_CHAR_1 = '1';
    int total = '+';
    int minus = '-';
    int count = 0;
    public int convert(int ch)
    try
    PrintWriter outfile = new PrintWriter("output.txt");
    if (ch == THE_CHAR_0)
    return ch;
    else
    if (ch == THE_CHAR_1)
    count++;
    if (count%2 == 1)
    ch = total;
    return (ch);
    else
    ch = minus;
    return (ch);
    }catch (FileNotFoundException e) {}
    return ch;
    }//method convert
    }//class AMIAny help would be appreicated.
    Thanks!

  • Coherence Help standalone java program put data in cache & Servlet to Read

    Hi,
    I have coherence 3.4 and using Oracle Application Server 10.1.3 We are in the process of developing a Web Application and want to use Coherence for caching the data. My Coherence is also installed on the same box as Oracle Application Server 10.1.3 need some help in storing the data in the coherence and reading it through the servlet. We have standalone java program that needs to put data in the cache and through servlet want to read that and display it on the page. When running the client the data is stored in the cache but when reading it through the servlet it returns null. We have included both coherence.jar and tangosol.jar in the war file and also in the path when running the standalone java program. Started the Coherence using the below command:
    C:\oracle\coherence\lib>java -cp coherence.jar -Dtangosol.coherence.cacheconfig=C:/oracle/coherence/tests/cache-config.xml com.tangosol.net.DefaultCacheServer
    here is the sample config file used when starting the server above:
    <?xml version="1.0"?>
    <!DOCTYPE cache-config SYSTEM "cache-config.dtd">
    <cache-config>
        <caching-scheme-mapping>
            <cache-mapping>
                <cache-name>VirtualCache</cache-name>
                <scheme-name>default-distributed</scheme-name>
            </cache-mapping>
        </caching-scheme-mapping>
        <caching-schemes>
            <!--
            Default Distributed caching scheme.
            -->
            <distributed-scheme>
                <scheme-name>default-distributed</scheme-name>
                <service-name>DistributedCache</service-name>
                <backing-map-scheme>
                    <class-scheme>
                        <scheme-ref>default-backing-map</scheme-ref>
                    </class-scheme>
                </backing-map-scheme>
            </distributed-scheme>
      <class-scheme>
                <scheme-name>default-backing-map</scheme-name>
                <class-name>com.tangosol.util.SafeHashMap</class-name>
                </class-scheme>
    </caching-schemes>
    </cache-config>And here is the standalone java program to put the data in the cache:
    import com.tangosol.net.CacheFactory;
    import com.tangosol.net.NamedCache;
    public class PutCache {
        public PutCache() {
        public static void main(String[] args) {
            PutCache putCache = new PutCache();
            NamedCache         cache = CacheFactory.getCache("VirtualCache");
            String key = "hello";
            cache.put(key, "Hello Cache123123");
    }And here is the Servlet code to read the data but it somehow returns null
    import com.tangosol.net.CacheFactory;
    import com.tangosol.net.NamedCache;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Servlet1 extends HttpServlet {
        private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            NamedCache         cache = CacheFactory.getCache("VirtualCache");
            String value = (String)cache.get("hello");
            out.println("<html>");
            out.println("<head><title>Servlet1</title></head>");
            out.println("<body>");
            out.println("<p>The servlet has received a GET. This is the reply.</p>"+value);
            out.println("</body></html>");
            out.close();
    }Is there any other configuration I need. Any help is really appreciated.
    Thanks

    Hi,
    While starting the coherence using
    C:\oracle\coherence\lib>java -cp coherence.jar -Dtangosol.coherence.cacheconfig=C:/oracle/coherence/tests/cache-config.xml com.tangosol.net.DefaultCacheServer
    while running standaone jave program using the below command
    java -Dtangosol.coherence.cacheconfig=C:/oracle/coherence/tests/cache-config.xml Populatecache
    In the Web Application don't have any reference to cache-config.xml just using the coherence.jar & tangosol.jar.
    What are the steps or configurations I need in order to connect to the same Coherence Cache. Do I need to provide some host:port for the Coherence for storing the data in the cache. How does the java client program and Web Application knows to connect to the Coherence. As currently even if I don't start the coherence server and just run the java standalone program it goes and executes fine wondering wher exactly does it persists the cache if coherence itself is not started or just adding the jars is enough. Any help is appreciated.
    Thanks

  • Need help with Java programming installation question

    Sorry for my lack of knowledge about Java programming, but:....
    A while back I thought I had updated my Java Runtime Environment programming. But I now apparently have two programs installed, perhaps through my not handling the installation properly. Those are:
    J2SE Runtime Environment 5.0 update 5.0 (a 118MB file)
    and:
    Java 2 Runtime Environment, SE v 1.4.2_05 (a 108MB file)
    Do I need both of these installed? If not, which should I uninstall?
    Or, should I just leave it alone, and not worry about it?
    Yeah, I don't have much in the way of technical knowledge...
    Any help or advice would be appreciated. Thank you.
    Bob VanHorst

    Thanks for the feedback. I think I'll do just that. Once in a while I have a problem with Java not bringing up a webcam shot, but when that happens, it seems to be more website based than a general condition.

  • Need help in java program execution...

    Hi all
    I have made a java program( JAR file) and I need to execute it from a double click...can you please tell how to do it..For normal execution i have to go to CMD prompt and write a couple of commands but i want to execute it through 1 click..
    The method which i thought was to make a batch(.bat) file and write the commands in it but its not working properly...do you have any other method or software which i can use...
    I am new to java and any help would be appreciated.

    You should avoid using a batch file since there's no explicit reason to do that.
    sachinmittal wrote:
    I have made a java program( JAR file) and I need to execute it from a double click...can you please tell how to do it.There a lot of tutorials out there. I prefer this one:
    [http://java.sun.com/docs/books/tutorial/deployment/jar/index.html]
    You should take look at the manifest section if you want to build an executable jar.

  • Help With Java Program Please!

    Greetings,
    I am trying to figure out to write a Java program that will read n lines of text from the keyboard until a blank line is read. And as it read each line, It's suppose to keep track of
    The longest string so far
    The Longest word seen so far
    The line that contains the most words
    The total number of words seen in all lines
    I don't know where to begin. Help me please! Thank you very much.

    Man I have to say that this smells like home work.
    Since you have not asked for a cut paste code I tell you what to do
    1. Write a function which take single string as a parameter and break it down to words and return words as a array or string
    (You can use this)
    you will need several variables to keep track of
    The longest string so far
    The Longest word seen so far
    The line that contains the most words and number of words in that line
    The total number of words seen in all lines
    now read lines in a loop if the length is 0 exit (that is your exis condition right)
    otherwise check the length of input string and update "The longest string so far"
    then break down the words and update "The Longest word seen so far", "The line that contains the most words and number of words in that line" and "The total number of words seen in all lines"
    and when you are exiting display the above values

  • How to read card reader (bar code reader) in simple java program ?

    hai all
    how to manipulate (read/write) card readers (or bar code reader ) in
    a java program ?
    should i import any particular package library ?
    pls give me any sample code or tutorials or tools, etc (whatever you have) .
    i am new to this card reader category
    its very urgent
    thank you .

    Nearly all card readers and barcode readers I've ever seen simply stick their input right onto stdin, so you can capture it just as if it had been typed in on a keyboard

  • Need help w java program

    i have to writea java program.
    write a java program to make change when an item that costs less than a dollar is purchased and the buyer gives the seller a one dollar bill. the goal is to provide the buyer as few coins as possible in the change. the program must determine how many quarters, how many dimes, how many nickles, and how many pennies to return. the ideal program would read in the cost of the item purchased, but for now your program should just set the cost of the item to be 32 cents.
    what am i supposed to do. thank you!!

    i only have to make the first step, which is showing that the item costs 32 cents.
    so far i got this:
    public class change {
    public static void main(String[] args) {
    System.out.println("Cost = $0.32);
    however, i get this error message:
    Could not find the main class: change. Program will exit.
    Exception in thread "main"
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    i downloaded jgrasp on my computer and i got this message, this never happened with the school pc. so maybe i did sth wrong with the program or i don't have the right software on my computer.

Maybe you are looking for

  • Segment count in EDIFACT ORDERS

    Hi, Can anyone advise which function to use to calculate the number of segment in the message trailer (EDIFACT D98A ORDERS UNT/0074)? Regards, Scott.

  • QUEUE locking problem

    I just made 2 sample programs, the first one writes in a queue and the other reads from the queue. It seem when one of the process die (ex kill -9) between a put or get operation, the locks persist blocking all the operations (corrupting the database

  • Km document iview as a related link in a page

    I have created a KM document iview which points to a pdf, assigned the iview to a page, it works fine. But if i try to assign it as a related link to another page, go to the page and click on the link in related links area the document does not come

  • Background change by time of day. (MX)

    I'm redesigning my MySpace page and would like to have a background of the an ocean/beach view with the sky in the background. It's just like your average background yet the picture changes depending on what time of day it is. So, if someone's viewin

  • How to increase photo size whilst viewing on HDTV using Airplay?

    Hello, I am using a new Apple iphone 4s with IOS 5.1 etc and I am trying to view photos on my HDTV in widescreen format via Apple TV (3rdGen) ... The video playback mirrored from the iphone in 1080P automatically appears in widesreen using the full s