Need help with a cash register program.

I'm a noob at JAVA, but having fun with i so far! I was wondering if anyone could help me with a school project I need to get done. I've done most of the work, but I can't get it to not display when I have zero results. What I mean is that the project requires you to create a cash register program that gives you change in 20's, 5's, and 1's for a hundred dollar bill. I get it to display the results, but if there are zero of any category, like in the last problem, I can't let it show. Could someone please help! Thank you in advance! Here's what I have so far (sorry about the rapidshare download ^_^;).
[http://rapidshare.de/files/39978938/project.java.html]

Zack,
The user should not see the line: 0 $5 bill(s)Then you need to detect the situation where no five dollars bills are included in the change, and suppress the output of that line.
I can read your mind... it's going something like "yeah well righto smartass, I knew that allready... my question was _HOW_ to make that happen...
And my answer to that is "I'm not telling you"... well, not straight out anyway, coz you'll actually learn more if your struggle a bit (but not too much) yourself...
So... I suggest you (at least) read through [this page|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/if.html] on the +if+ statement, and maybe even try out the examples, which should (I imagine) take maybe half an hour or so. "Selection" is an absolutely core programming construct... and the concept is common to every programming language ever (AFAIK) invented... meaning that you will really struggle until you "get" the +if+ statement... so that half hour would be time well spent.
When you've got +if+ concept onboard, you can attempt to apply it to your immediate problem, suppressing those annoying fivers! Have a go yourself, if get really stumped than post a _specific_ question here about the bit that's stumped you.
I know it can be frustrating... but that just hightens the little thrill you get when you "get it".
Cheers. Keith.

Similar Messages

  • I need help with TV Capture Card program

    Hello,
    I want to create a JAVA program so I can schedule that the recording with my TV Capture Card begins in x seconds.
    Now to start a recording, you must press Ctrl+M and to stop an recording you must click the mouse.
    How can I realise that a Java application can "press" Ctrl+M. I have to create an timer, that must be do-able... but I don't know how the program can simulate the pressing of Ctrl+M. I also need to know how the Java program can do a mouse click for me to end the recording.
    Thanks in advance for helping me.
    Chris.

    Thank you... I think this was exactly what I needed.

  • I need help with the Bon Scott program

    Help me! I am learning Java from the book, "Teach Yourself Java through Osmosis" and I am having trouble with the Bon Scott program. Everytime I run it, which has been ca. 2 billion, it prints out, "Some balls are held for charity and some for fancy dress, but when they're held for pleasure, they're the balls that I like the best." It then proceeds to get pissed and finally vomits.
    Any suggestions ?

    What color is the vomit? That is, exactly what does it do when it gets pissed and vomits?

  • I need help with a lab from programming.

    I need the following tasks implemented in the code I wrote below. I would really appreciate if someone could achieve this because it would help me understand the coding process for the next code I have to write. Below are the four classes of code I have so far.
    save an array of social security numbers to a file
    read this file and display the social security numbers saved
    The JFileChooser class must be used to let the user select files for the storage and retrieval of the data.
    Make sure the code handles user input and I/O exceptions properly. This includes a requirement that the main() routine does not throw any checked exceptions.
    As a part of the code testing routine, design and invoke a method that compares the data saved to a file with the data retrieved from the same file. The method should return a boolean value indicating whether the data stored and retrieved are the same or not.
    * SSNArray.java
    * Created on February 28, 2008, 9:45 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package exceptionhandling;
    import java.util.InputMismatchException; // program uses class InputMismatchException
    import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName;
    * @author mer81348
    public class SSNArray
        public static int SOCIAL_SECURITY_NUMBERS = 10;
        private String[] socialArray = new String[SOCIAL_SECURITY_NUMBERS];
        private int socialCount = 0;
        /** Creates a new instance of SSNArray */
        public SSNArray ()
        public SSNArray ( String[] ssnArray, int socialNumber )
            socialArray = ssnArray;
            socialCount = socialNumber;
        public int getSocialCount ()
            return socialCount;
        public String[] getSocialArray ()
            return socialArray;
        public void addSocial ( String index )
            socialArray[socialCount] = index;
            socialCount++;
        public String toString ()
            StringBuilder socialString = new StringBuilder ();
            for ( int stringValue = 0; stringValue < socialCount; stringValue++ )
                socialString.append ( String.format ("%6d%32s\n", stringValue, socialArray[stringValue] ) );
            return socialString.toString ();
        public void validateSSN ( String socialInput ) throws InputMismatchException, DuplicateName
            if (socialInput.matches ("\\d{9}"))
                return;
            else
                throw new InputMismatchException ("ERROR! Incorrect data format");       
    * SSNArrayTest.java
    * Created on February 28, 2008, 9:46 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package exceptionhandling;
    import java.util.InputMismatchException; // program uses class InputMismatchException
    import java.util.Scanner; // program uses class Scanner
    import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName;
    * @author mer81348
    public class SSNArrayTest
        /** Creates a new instance of SSNArrayTest */
        public SSNArrayTest ()
         * @param args the command line arguments
        public static void main (String[] args)
            // create Scanner to obtain input from command window
            Scanner input = new Scanner ( System.in );
            System.out.printf ( "\nWELCOME TO SOCIAL SECURITY NUMBER CONFIRMER\n" );
            SSNArray arrayStorage = new SSNArray ();
            for( int socialNumber = 0; socialNumber < SSNArray.SOCIAL_SECURITY_NUMBERS; )
                String socialString = ( "\nPlease enter a Social Security Number" );
                System.out.println (socialString);
                String socialInput = input.next ();
                try
                    arrayStorage.validateSSN (socialInput);
                    arrayStorage.addSocial (socialInput);
                    socialNumber++;
                catch (InputMismatchException e)
                    System.out.println ( "\nPlease reenter Social Security Number\n" + e.getMessage() );
                catch (DuplicateName e)
            System.out.printf ("\nHere are all your Social Security Numbers stored in our database:\n");
            System.out.printf ( "\n%8s%32s\n", "Database Index", "Social Security Numbers" );
            System.out.println (arrayStorage);
    * SSNArrayExpanded.java
    * Created on February 28, 2008, 9:52 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package exceptionhandling;
    import java.util.InputMismatchException;
    import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName;
    * @author mer81348
    public class SSNArrayExpanded extends SSNArray
        /** Creates a new instance of SSNArrayExpanded */
        public SSNArrayExpanded ()
        public SSNArrayExpanded ( String[] ssnArray, int socialNumber )
            super ( ssnArray, socialNumber );
        public void validateSSN ( String socialInput ) throws InputMismatchException, DuplicateName
            super.validateSSN (socialInput);
                int storedSocial = getSocialCount ();
                for (int socialMatch = 0; socialMatch < storedSocial; socialMatch++ )
                    if (socialInput.equals (getSocialArray () [socialMatch]))
                        throw new DuplicateName ();
            return;
    * SSNArrayTestExpanded.java
    * Created on February 28, 2008, 9:53 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package exceptionhandling;
    import java.util.InputMismatchException; // program uses class InputMismatchException
    import java.util.Scanner; // program uses class Scanner
    import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName;
    * @author mer81348
    public class SSNArrayTestExpanded
        /** Creates a new instance of SSNArrayTest */
        public SSNArrayTestExpanded ()
         * @param args the command line arguments
        public static void main (String[] args)
            // create Scanner to obtain input from command window
            Scanner input = new Scanner ( System.in );
            System.out.printf ( "\nWELCOME TO SOCIAL SECURITY NUMBER CONFIRMER\n" );
            SSNArrayExpanded arrayStorage = new SSNArrayExpanded(); 
            for( int socialNumber = 0; socialNumber < SSNArray.SOCIAL_SECURITY_NUMBERS; )
                String socialString = ( "\nPlease enter a Social Security Number" );
                System.out.println (socialString);
                String socialInput = input.next ();
                try
                    arrayStorage.validateSSN (socialInput);
                    arrayStorage.addSocial (socialInput);
                    socialNumber++;
                catch (InputMismatchException e)
                catch (DuplicateName e)
                    System.out.println ( "\nSocial Security Number is already claimed!\n" + "ERROR: " + e.getMessage() ); 
            System.out.printf ("\nHere are all your Social Security Numbers stored in our database:\n");
            System.out.printf ( "\n%8s%32s\n", "Database Index", "Social Security Numbers" );
            System.out.println (arrayStorage);
    }

    cotton.m wrote:
    >
    That writes creates the file but it doesn't store the social security numbers.True.Thanks for confirming that...
    How do I get it to save?
    Also, in the last post I had the write method commented out, the correct code is:
         System.out.printf ("\nHere are all your Social Security Numbers stored in our database:\n");
            System.out.printf ( "\n%8s%32s\n", "Database Index", "Social Security Numbers" );
            System.out.println ( arrayStorage );
            try
                File file = new File ("Social Security Numbers.java");
                // Create file if it does not exist
                boolean success = file.createNewFile ();
                if (success)
                      PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Social Security Numbers.txt")));               
    //                BufferedWriter out = new BufferedWriter (new FileWriter ("Social Security Numbers.txt")); 
                    out.write( "what goes here ?" );
                    out.close ();
                    // File did not exist and was created
                else
                    // File already exists
            catch (IOException e)
            System.exit (0);
    }It still doesn't write.

  • Need help with a vowel reading program :(

    Hi, im trying to create a program that does the following:
    "a program that reads a list of vowels (a, e, i, o, u) and stores them in an array. The maximum number of vowels to be read should be obtained from the user before beginning to read the vowels, however, the user may cancel the reading of vowels at any time by entering '#'. The algorithm should then count and display the number of times each vowel appears in the array. Finally the algorithm should also output the index in the array where the each vowel first appeared or a suitable message if a particular vowel is not in the array at all."
    It says to store the input in an array so I've probably started all wrong :( but any help at all would be greatly accepted.
    Im trying to go through it doing one method at a time but im having trouble with the reading input method
    the 1 error i get is marked with ***.
    Is it that I need to do a for loop first to find the length of the string?
    import java.io.*;
    import javax.swing.JOptionPane;
    class prac7
          public static String readIn()
                    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
                    String max = null;
                    String sentence = null;
               try
                    System.out.println("\nEnter the amount of characters to read in: ");
                    max = input.readLine();
                    int total = Integer.parseInt(max);
               catch(Exception e) {System.out.println("invalid");}
               do
                    sentence = JOptionPane.showInputDialog("Enter a sentence, ("+max+" characters maximum): ");
                    int ind = sentence.length();
               }while(ind <= max);     //*** the arrow is under 'ind' and says "cannot resolve symbol"
               return sentence;
          public static void main(String[] args)
               String data = "";
               data = readIn();
          }Thanks.

    thanks for your reply Paul ^^ , but im still having trouble with that part of the program :(
    Its saying "operator <= cannot be applied to int,java.lang.String" (Ive marked in asterisks)
    Also i've add the rest of the program code, but in the calcPrint method i am having trouble understanding some of it (some of the code was used from another program) and it would be great if someone could show me a more simplier way of coding the same thing? even if its more typing, i just want to understand it better.
    (i've marked the area im having trouble understanding with asterisks)
    Once again any help would be fantastic :)
    here is the code
    import java.io.*;
    import javax.swing.JOptionPane;
    class prac7
          public static String readIn()
               BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
               String max = null;
               String sentence = null;
               try
                    System.out.println("\nEnter the amount of characters to read in: ");
                    max = input.readLine();
                    int total = Integer.parseInt(max);
               catch(Exception e) {System.out.println("invalid");}
               do
                    sentence = JOptionPane.showInputDialog("Enter a sentence, ("+max+" characters maximum): ");
                    sentence.toLowerCase();
               }while(sentence.length() <= max);     /******operator error******/
               return sentence;
          public static void calcPrint(String data)
               String vowels[] = {"a","e","i","o","u","Other letters"};
               String screen = "";
               int alpha[] = new int [6];
               for (int i = 0; i < data.length(); i++)
               /********from here*********/
                    try
                         alpha["aeiou".indexOf(data.charAt(i))]++;
                         if(data.charAt(i) != ' ') alpha[5]++;
                    catch(Exception e){}
               for (int i = 0; i < alpha.length; i++)
               screen += vowels[i]+" Amount = "+alpha[i]+"\n";
              /**********to here**********/
               JOptionPane.showMessageDialog(null,screen);
          public static void main(String[] args)
               String data = "";
               data = readIn();
               calcPrint(data);
    }

  • I need help with closing a running program. It seems like it does not count as a program. Tried to turn of the computer and closing all programs. Please help!?

    I have a problem with a grey text box. It writes and says all i do. For example: When i now write it says all the letters one for one. If i open a new rogram it says so. If i click on something it gives me information about it. I can click the box and drag it, but dont close it. I have restarted the computer and closing all windows and programs. It just popped out when i was pressing some buttons on the mac. I think it is a easy way to fix it, but i cant find out what it is named and search for it. I think it is made for help and i did not download anything to get it. If i change user on the mac it does go away when I am on the other user, but i really want to keep the one i have because off all the settings and programs i have.
    Please reply if you know anything about this.
    This is a printscreen of the box, the language is Norwegian if someone wonder...
    It is really annoying, I hope someone can help me out.

    Oh thanks alot! Really happy that people take the time to answer my `noob`questions! Would not find that out by my own.
    Thanks!

  • Need help with running a Java program on Linux

    I am trying to get a Java program to run on a Linux machine. The program is actually meant for a Mac computer. I want to see if someone with Java experience can help me determine what is causing the program to stall. I was successful in getting it installed on my Linux machine and to partially run.
    The program is an interface to a database. I get the login screen to appear, but then once I enter my information and hit enter the rest of the program never shows, however, it does appear to connect in the background.
    Here is the error when I launch the .jar file from the command screen:
    Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    I am not a programmer and I am hoping this will make some sense to someone. Any help in resolving this is greatly appreciated!

    Well, without knowing a little bit about programming, and how to run your debugger, I don't think you're going to fix it. The IllegalArgumentException is saying that some call does not like what it's getting. So you'll have to go in an refactor at least that part of the code.

  • Need help with java.nio.socket program.

    Can someone please help me here? I am trying to create a class that listens on a socket for an incoming connection, but I am getting the following error on compile:
    SocketIn.java:48: incompatible types
    found : java.nio.channels.SocketChannel
    required: java.net.Socket
    Socket requestSocket = requestChannel.accept();
    Here is my code:
    package NETC;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    public class SocketIn{
         // Buffer for any incoming data.
         private static ByteBuffer inBuffer = ByteBuffer.allocateDirect(1024);
         CharBuffer charBuffer = null;
         public SocketIn(int intPort)throws Exception{
              // Create a non-blocking server socket.
              ServerSocketChannel serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking(false);
              // Use the host and port to bind the server socket.
              InetAddress inetAddress = InetAddress.getLocalHost();
              InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, intPort);
              serverChannel.socket().bind(socketAddress);
              // The selector for incoming requests.
              Selector requestSelector = SelectorProvider.provider().openSelector();
              // Put the server socket on the selectors 'ready list'.
              serverChannel.register(requestSelector, SelectionKey.OP_ACCEPT);
              while(requestSelector.select() > 0){
                   System.out.println("Connection Accepted...");
                   // A request has been made and is ready for IO.
                   Set requestKeys = requestSelector.selectedKeys();
                   Iterator iterator = requestKeys.iterator();
                   while(iterator.hasNext()){
                        SelectionKey requestKey = (SelectionKey)iterator.next();
                        // Get the socket that's ready for IO.
                        ServerSocketChannel requestChannel = (ServerSocketChannel)requestKey.channel();
                        // This shouldn't block.
                        Socket requestSocket = requestChannel.accept();
                        inBuffer.clear();
                        requestSocket.read(inBuffer);                    
                        inBuffer.flip();
                        Charset charset = Charset.forName("ISO-8859-1");
                        CharsetDecoder decoder = charset.newDecoder();
                        charBuffer = decoder.decode(inBuffer);
                        iterator.remove();                    
    }

    Well its been about a month and a half so I guess you have your answer. In case you don't...
    // This shouldn't block.
    Socket requestSocket = requestChannel.accept();
    The problem is quite simple. The ServerSocketChannel.accept() returns a SocketChannel. (Channel -> Channel).
    You can get access to the socket using the SocketChannel.
    SocketChannel requestSocketChannel = requestChannel.accept();
    Socket requestSocket = requestSocketChannel.socket();
    But you don't need the socket to read and write.

  • Need help with solving the (basic) programming error

    I'm reaaaaaaaaaally new to Java and programming in general. I've been glancing through my older brother's old stuff (he's back at Uni!) and I've taken an interest.
    Anyways, so I'm trying to finish this really simple program cause I wanna wow some friends ("wow" = "haha we've done this before a gazillion times") but I can't seem to solve this "incompatible lines" bug in the code, specifically line 24. I've been looking at it for exactly 4 hours!! Programming in Java 1.6.
    Thanks for the help!! :)
    import java.util.*;
    import java.util.Scanner;
    public class LuigisPizzaProgram {
         public static void main(String args[]) {
         System.out.println("Luigi's Pizza");
         System.out.println("-------------------------------------------");
         System.out.println(" a(SML) b(MED) c(LRG)");
         System.out.println("1. Cheese 5.00 7.50 10.00");
         System.out.println("2. Pepperoni 5.75 8.63 11.50");
         System.out.println("3. Combination 6.50 9.75 13.00");
         System.out.println("4. Vegetarian 7.25 10.88 14.50");
         System.out.println("5. Meat Lovers 8.00 12.00 16.00");
         System.out.println(" ");
         System.out.println("What kind of pizza do you want?");     
         int kind = new Scanner(System.in).nextInt();
         System.out.println(kind);
         System.out.println("What size of pizza do you want?");
         char size = new Scanner(System.in).nextLine();
         System.out.println(size);
         }

    Having said that, it is nontraditional to use Scanner like you are using it. There is no way to reuse it in order to get more input. Better would be something like:
            System.out.println("What size of pizza do you want?");
            Scanner scan = new Scanner(System.in);  // create the scan variable
            String size = scan.nextLine(); // now use the scan variable
            System.out.println(size);Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
      // your code block goes here.
    &#91;/code&#93;good luck, pete

  • Need Help with BI Beans Sample Programs

    I am trying to use the print and export functions that are described in the BI Beans sample program. I need to make a small change and don't know how to do it. I would like to open the print or export page in a new window instead of on top of the current page. Any ideas on how to do this? Thanks.

    first hit on google
    thankyou for using the georgemc google proxy

  • Need help with a magic square program

    Hi, I have to write a code that prints out first 10 magic square numbers
    -- magic square numbers: numbers that is a perfect square and sum of consecutive integers (like 36 -- 6 squared or sum of 1 to 8)
    here's my code:
    public class Loop {
    public static void magicSquare ()
    long inc = 0;
    long integer = 0;
    long total = 0;
    for (int square =1; square>0; square++)
    total = square*square;
    int sum = 0;
    for (int i = 1; i>0; i++)
    if (sum<total){
    sum += i;
    else if (sum==total){
    System.out.println("Magic Square is: " + total);
    break;
    else {
    break;
    I have a simple seperate driver

    Merge - you have two lists, a list of squares (implicit list, you just remember the last square and what you need to increment to the next one), and a list of triangles (sums of n consecutive numbers starting at 1 are triangular numbers).
    As long as the head of one list is below the other you increment it. When the two heads coincide you have a squareTriangle.
    It ran pretty quickly on my machine, so it is probably not worth telling you how the whole thing can be reduced to pells equation and how the numbers represent successive rational approximations to the square root of 8. Continued fractions rule and are where you would go if you needed to go faster than this - but 0 seconds (which has to be a lie caused by round off error) seems good enough
      static void spewSquareTriangles(int n){
        long q = 0; // first square
        long t = 0; // first triangle
        long iq = 1;
        long it = 1;
        for(int i = 0; i<n;){
          if(q == t){
            System.out.println(i + ": " + q);
            q += iq; iq += 2; // squares increment by odd numbers 1+3 = 4;+5 = 9;+7 =16 ...
            t += it++;    // triangles increment by each number
            i++;
          } else {
            if(t < q){t += it++;} else {q += iq; iq += 2;}
        public static void main(String[] args) {
          spewSquareTriangles(10); 
    compile:
    run:
    0: 0
    1: 1
    2: 36
    3: 1225
    4: 41616
    5: 1413721
    6: 48024900
    7: 1631432881
    8: 55420693056
    9: 1882672131025
    BUILD SUCCESSFUL (total time: 0 seconds)

  • Need Help With Something In ICloud Program

    I am trying to figure out if there is anyway possible I can save all my photos into ICloud? I keep
    looking on the Apple homepage and all it talks about is photo storage in ICloud.  I can't even find
    anything in my ICloud about photo storage. If anybody has any idea how to do this can you please help
    me tonight.

    Hey TrishaA2466,
    Based on your description, it sounds like you may be talking about the new iCloud Photo Library beta feature. If you are looking for more information on this new feature, you may find the following pages and articles helpful:
    Apple - iCloud - Photos
    iCloud Photo Library beta FAQ - Apple Support
    Cheers,
    - Brenden

  • Need help with an SHDB BDC program  for Change outbound delivery(VL02N).

    I have created recording to change outbound delivery(VL02N). Steps are as below-
    For VL02N recording 1st I have click on the header(F8) then dates tab.
    Then insert line (+ button) then it shows 8 transport types.
    I have chosen 7th transport type. In SHDB it shows BDC_CURSOR = '08/07'.
    Then I have created BDC program for this recording, but it's not working,
    because It is changing BDC_CURSOR value every time when we do SHDB or VL02N and in my code I have hard coded BDC_CURSOR = '08/07' . 
    Can anyone tell me how to get this BDC_CURSOR changed value. So that instead of hard coding this value I can select this value every time.
    (FYI      For this Screen name = SAPMSSY0 Screen No = 0120.)
    Thanks.

    I have created recording to change outbound delivery(VL02N). Steps are as below-
    For VL02N recording 1st I have click on the header(F8) then dates tab.
    Then insert line (+ button) then it shows 8 transport types.
    I have chosen 7th transport type. In SHDB it shows BDC_CURSOR = '08/07'.
    Then I have created BDC program for this recording, but it's not working,
    because It is changing BDC_CURSOR value every time when we do SHDB or VL02N and in my code I have hard coded BDC_CURSOR = '08/07' . 
    Can anyone tell me how to get this BDC_CURSOR changed value. So that instead of hard coding this value I can select this value every time.
    (FYI      For this Screen name = SAPMSSY0 Screen No = 0120.)
    Thanks.

  • Need Help With File Matching Records

    I need help with my file matching program.
    Here is how it suppose to work: FileMatch class should contain methods to read oldmast.txt and trans.txt. When a match occurs (i.e., records with the same account number appear in both the master file and the transaction file), add the dollar amount in the transaction record to the current balance in the master record, and write the "newmast.txt" record. (Assume that purchases are indicated by positive amounts in the transaction file and payments by negative amounts.)
    When there is a master record for a particular account, but no corresponding transaction record, merely write the master record to "newmast.txt". When there is a transaction record, but no corresponding master record, print to a log file the message "Unmatched transaction record for account number ..." (fill in the account number from the transaction record). The log file should be a text file named "log.txt".
    Here is my following program code:
    // Exercise 14.8: CreateTextFile.java
    // creates a text file
    import java.io.FileNotFoundException;
    import java.lang.SecurityException;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import org.egan.AccountRecord;
    import org.egan.TransactionRecord;
    public class CreateTextFile
      private Formatter output1;  // object used to output text to file
      private Formatter output2;  // object used to output text to file
      // enable user to open file
      public void openTransFile()
        try
          output1 = new Formatter("trans.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openTransFile
      // enable user to open file
      public void openOldMastFile()
        try
          output2 = new Formatter("oldmast.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openOldMastFile
      // add transaction records to file
      public void addTransactionRecords()
        // object to be written to file
        TransactionRecord record1 = new TransactionRecord();
        Scanner input1 = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
          "To terminate input, type the end-of-file indicator",   
          "when you are prompted to enter input.",
          "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
          "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s\n%s",
           "Enter account number (> 0) and amount.","? ");
        while (input1.hasNext())  // loop until end-of-file indicator
          try // output values to file
            // retrieve data to be output
            record1.setAccount(input1.nextInt());    // read account number
            record1.setAmount(input1.nextDouble());  // read amount
            if (record1.getAccount() > 0)
              // write new record
              output1.format("%d %.2f\n", record1.getAccount(), record1.getAmount());
            } // end if
            else
              System.out.println("Account number must be greater than 0.");
            } // end else
          } // end try
          catch (FormatterClosedException formatterClosedException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input1.nextLine(); // discard input so user can try again
          } // end catch
          System.out.printf("%s %s\n%s", "Enter account number (> 0) ",
            "and amount.","? ");
        } // end while
      } // end method addTransactionRecords
      // add account records to file
      public void addAccountRecords()
        // object to be written to file
        AccountRecord record2 = new AccountRecord();
        Scanner input2 = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
          "To terminate input, type the end-of-file indicator",   
          "when you are prompted to enter input.",
          "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
          "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s\n%s",
           "Enter account number (> 0), first name, last name and balance.","? ");
        while (input2.hasNext())  // loop until end-of-file indicator
          try // output values to file
            // retrieve data to be output
            record2.setAccount(input2.nextInt());    // read account number
            record2.setFirstName(input2.next());      // read first name
            record2.setLastName(input2.next());       // read last name
            record2.setBalance(input2.nextDouble());  // read balance
            if (record2.getAccount() > 0)
              // write new record
              output2.format("%d %s %s %.2f\n", record2.getAccount(), record2.getFirstName(),
                record2.getLastName(), record2.getBalance());
            } // end if
            else
              System.out.println("Account number must be greater than 0.");
            } // end else
          } // end try
          catch (FormatterClosedException formatterClosedException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input2.nextLine(); // discard input so user can try again
          } // end catch
          System.out.printf("%s %s\n%s", "Enter account number (> 0),",
            "first name, last name and balance.","? ");
        } // end while
      } // end method addAccountRecords
      // close file
      public void closeTransFile()
        if (output1 != null)
          output1.close();
      } // end method closeTransFile
      // close file
      public void closeOldMastFile()
        if (output2 != null)
          output2.close();
      } // end method closeOldMastFile
    } // end class CreateTextFile--------------------------------------------------------------------------------------------------
    // Exercise 14.8: CreateTextFileTest.java
    // Testing class CreateTextFile
    public class CreateTextFileTest
       // main method begins program execution
       public static void main( String args[] )
         CreateTextFile application = new CreateTextFile();
         application.openTransFile();
         application.addTransactionRecords();
         application.closeTransFile();
         application.openOldMastFile();
         application.addAccountRecords();
         application.closeOldMastFile();
       } // end main
    } // end class CreateTextFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.8: TransactionRecord.java
    // A class that represents on record of information
    package org.egan; // packaged for reuse
    public class TransactionRecord
      private int account;
      private double amount;
      // no-argument constructor calls other constructor with default values
      public TransactionRecord()
        this(0,0.0); // call two-argument constructor
      } // end no-argument AccountRecord constructor
      // initialize a record
      public TransactionRecord(int acct, double amt)
        setAccount(acct);
        setAmount(amt);
      } // end two-argument TransactionRecord constructor
      // set account number
      public void setAccount(int acct)
        account = acct;
      } // end method setAccount
      // get account number
      public int getAccount()
        return account;
      } // end method getAccount
      // set amount
      public void setAmount(double amt)
        amount = amt;
      } // end method setAmount
      // get amount
      public double getAmount()
        return amount;
      } // end method getAmount
    } // end class TransactionRecord -------------------------------------------------------------------------------------------------
    // Exercise 14.8: AccountRecord.java
    // A class that represents on record of information
    package org.egan; // packaged for reuse
    import org.egan.TransactionRecord;
    public class AccountRecord
      private int account;
      private String firstName;
      private String lastName;
      private double balance;
      // no-argument constructor calls other constructor with default values
      public AccountRecord()
        this(0,"","",0.0); // call four-argument constructor
      } // end no-argument AccountRecord constructor
      // initialize a record
      public AccountRecord(int acct, String first, String last, double bal)
        setAccount(acct);
        setFirstName(first);
        setLastName(last);
        setBalance(bal);
      } // end four-argument AccountRecord constructor
      // set account number
      public void setAccount(int acct)
        account = acct;
      } // end method setAccount
      // get account number
      public int getAccount()
        return account;
      } // end method getAccount
      // set first name
      public void setFirstName(String first)
        firstName = first;
      } // end method setFirstName
      // get first name
      public String getFirstName()
        return firstName;
      } // end method getFirstName
      // set last name
      public void setLastName(String last)
        lastName = last;
      } // end method setLastName
      // get last name
      public String getLastName()
        return lastName;
      } // end method getLastName
      // set balance
      public void setBalance(double bal)
        balance = bal;
      } // end method setBalance
      // get balance
      public double getBalance()
        return balance;
      } // end method getBalance
      // combine balance and amount
      public void combine(TransactionRecord record)
        balance = (getBalance() + record.getAmount()); 
      } // end method combine
    } // end class AccountRecord -------------------------------------------------------------------------------------------------
    // Exercise 14.8: FileMatch.java
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import org.egan.AccountRecord;
    import org.egan.TransactionRecord;
    public class FileMatch
      private Scanner inTransaction;
      private Scanner inOldMaster;
      private Formatter outNewMaster;
      private Formatter theLog;
      // enable user to open file
      public void openTransFile()
        try
          inTransaction = new Scanner(new File("trans.txt"));
        } // end try
        catch (FileNotFoundException fileNotFoundException)
          System.err.println("Error opening file.");
          System.exit(1);
        } // end catch
      } // end method openTransFile
      // enable user to open file
      public void openOldMastFile()
        try
          inOldMaster = new Scanner(new File("oldmast.txt"));
        } // end try
        catch (FileNotFoundException fileNotFoundException)
          System.err.println("Error opening file.");
          System.exit(1);
        } // end catch
      } // end method openOldMastFile
      // enable user to open file
      public void openNewMastFile()
        try
          outNewMaster = new Formatter("newmast.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openNewMastFile
      // enable user to open file
      public void openLogFile()
        try
          theLog = new Formatter("log.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openLogFile
      // update records
      public void updateRecords()
        TransactionRecord transaction = new TransactionRecord();
        AccountRecord account = new AccountRecord();
        try // read records from file using Scanner object
          System.out.println("Start file matching.");
          while (inTransaction.hasNext() && inOldMaster.hasNext())
            transaction.setAccount(inTransaction.nextInt());     // read account number
            transaction.setAmount(inTransaction.nextDouble());   // read amount
            account.setAccount(inOldMaster.nextInt());     // read account number
            account.setFirstName(inOldMaster.next());      // read first name 
            account.setLastName(inOldMaster.next());       // read last name
            account.setBalance(inOldMaster.nextDouble());  // read balance
            if (transaction.getAccount() == account.getAccount())
              while (inTransaction.hasNext() && transaction.getAccount() == account.getAccount())
                account.combine(transaction);
                outNewMaster.format("%d %s %s %.2f\n",
                account.getAccount(), account.getFirstName(), account.getLastName(),
                account.getBalance());
                transaction.setAccount(inTransaction.nextInt());     // read account number
                transaction.setAmount(inTransaction.nextDouble());   // read amount
            else if (transaction.getAccount() != account.getAccount())
              outNewMaster.format("%d %s %s %.2f\n",
              account.getAccount(), account.getFirstName(), account.getLastName(),
              account.getBalance());         
              theLog.format("%s%d","Unmatched transaction record for account number ",transaction.getAccount());
          } // end while
          System.out.println("Finish file matching.");
        } // end try
        catch (NoSuchElementException elementException)
          System.err.println("File improperly formed.");
          inTransaction.close();
          inOldMaster.close();
          System.exit(1);
        } // end catch
        catch (IllegalStateException stateException)
          System.err.println("Error reading from file.");
          System.exit(1);
        } // end catch   
      } // end method updateRecords
      // close file and terminate application
      public void closeTransFile()
        if (inTransaction != null)
          inTransaction.close();
      } // end method closeTransFile
      // close file and terminate application
      public void closeOldMastFile()
        if (inOldMaster != null)
          inOldMaster.close();
      } // end method closeOldMastFile
      // close file
      public void closeNewMastFile()
        if (outNewMaster != null)
          outNewMaster.close();
      } // end method closeNewMastFile
      // close file
      public void closeLogFile()
        if (theLog != null)
          theLog.close();
      } // end method closeLogFile
    } // end class FileMatch-------------------------------------------------------------------------------------------------
    // Exercise 14.8: FileMatchTest.java
    // Testing class FileMatch
    public class FileMatchTest
       // main method begins program execution
       public static void main( String args[] )
         FileMatch application = new FileMatch();
         application.openTransFile();
         application.openOldMastFile();
         application.openNewMastFile();
         application.openLogFile();
         application.updateRecords();
         application.closeLogFile();
         application.closeNewMastFile();
         application.closeOldMastFile();
         application.closeTransFile();
       } // end main
    } // end class FileMatchTest-------------------------------------------------------------------------------------------------
    Sample data for master file:
    Master file                         
    Account Number            Name                     Balance
    100                            Alan Jones                   348.17
    300                            Mary Smith                    27.19
    500                            Sam Sharp                   0.00
    700                            Suzy Green                   -14.22Sample data for transaction file:
    Transaction file                    Transaction
    Account Number                  Amount
    100                                         27.14
    300                                         62.11
    300                                         83.89
    400                                         100.56
    700                                         80.78
    700                                         1.53
    900                                         82.17  -------------------------------------------------------------------------------------------------
    My FileMatch class program above has bugs in it.
    The correct results for the newmast.txt:
    100  Alan  Jones  375.31
    300  Mary  Smith  173.19
    500  Sam  Sharp  0.00
    700  Suzy Green  68.09The correct results for the log.txt:
    Unmatched transaction record for account number 400Unmatched transaction record for account number 900------------------------------------------------------------------------------------------------
    My results for the newmast.txt:
    100 Alan Jones 375.31
    300 Mary Smith 111.08
    500 Sam Sharp 0.00
    700 Suzy Green -12.69My results for the log.txt
    Unmatched transaction record for account number 700-------------------------------------------------------------------------------------------------
    I am not sure what is wrong with my code above to make my results different from the correct results.
    Much help is appreciated. Please help.

    From the output, it looks like one problem is just formatting -- apparently you're including a newline in log entries and not using tabs for the newmast output file.
    As to why the numbers are off -- just from glancing over it, it appears that the problem is when you add multiple transaction values. Since account.combine() is so simple, I suspect that you're either adding creating transaction objects incorrectly or not creating them when you should be.
    Create test input data that isolates a single case of this (e.g., just the Mary Smith case), and then running your program in a debugger or adding debugging code to the add/combine method, so you can see what's happening in detail.
    Also I'd recommend reconsidering your design. It's a red flag if a class has a name with "Create" in it. Classes represent bundles of independant state and transformations on that state, not things to do.

  • I need help with re installing my apple account for itunes.

    Had problems with my itune account, so I uninstalled and now need help with re-installing the program with the songs I have already purchased.

    Your iTunes account is something at the iTunes Store online.  It is not possible to uninstall it.  Do you mean the iTunes application?  Even if you delete the application and restore it, it should not have deleted your iTunes library (essentially the contents of the iTunes folder in Music) on your computer unless you did a separate steep and specifically deleted that too.  You need to tell us what it was you deleted.

Maybe you are looking for

  • IPod no longer Authorized, since OS 4.3 upgrade

    A little bit of history first- iPod touch is 1 year old (3rd gen). Until a week ago, I have had no problems syncing it with iTunes. All of a sudden, after the iOS 4.3 upgrade, next time I connected for Sync, I get: This computer is no longer authoriz

  • Running a Bat file from a stored procedure

    This is part II of Re: Need to run bat file from application express I thought I would open a new thread I thought I had this fiqured out but it still doesn't work 1) I granted CREATE EXTERNAL JOB to my user 2) startup the OracleJobScheduler Service

  • How to do a specific report

    Hello! I have an assignment to do. In my dashboard page I have a time prompt with this format (25/06/2011) and I want to do a chart with axis X with all days of month of my prompt. I mean, if user select in page prompt (25/06/2011) I should see in my

  • Can Video widgets start and stop when entering and exiting the browser viewport?

    I like to use multiple autoplaying/looping video clips on a single page but I need to figure out how to make the videos start only when they enter the viewport on a browser and stop after they exit the viewport. Does anyone know a way to do this?

  • ISE licenses and Profiling service

    Hi, I tried to find proper explanation of how ISE licenses are used but I am still not sure of one thing. With the Plus license, when the profiling service is turned on; is the number of endpoints consumed from the Plus license for every endpoint tha