CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: reading input

  1. #1
    Join Date
    Apr 2009
    Posts
    7

    reading input

    Ok so I am trying to write a simple program that will add or subtract from an amount (balance to a checking account) by typing in a number.

    For example:

    if I type 500 then the program will add 500
    if I type -500 then it will decrease 500
    it will continue to let you input numbers until you end the program at which point it will display your balance
    and to end this program i would simply type 0

    I am fairly new to progamming so I am sorry if I am sounding stupid here or if I am not using the correct terms.

    So this is what I have so far....

    //create a scanner
    Scanner input = new Scanner(System.in);

    //prompt user for balance
    System.out.println("Please input your checking account information ");
    System.out.println();
    float balance = 0;
    int end = 1;

    while(end != 0){
    if (input.nextFloat() == 0){
    end = 0;
    }
    balance = balance + input.nextFloat();

    }

    System.out.println(balance);


    now my problem right now seems to be with the while loop or the if statement inside it(maybe I should be using something different here). What I cannot figure out is how to end the program by pressing 0 while allowing someone to continue adding or subtracting till they press 0. Any pointers on where I should go from here or what I should change?

  2. #2
    Join Date
    Jul 2008
    Posts
    70

    Re: reading input

    You are reading input.nextFloat() from the stream twice. This is not what you want. You need to store it in a temp variable.

    Example:
    Code:
      while (end != 0)
            {
                float nextFloat = input.nextFloat();
                if (nextFloat == 0 )
                {
                    end = 0;
                }
                balance = balance + nextFloat;
    
            }

  3. #3
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: reading input

    Or you could do:

    Code:
        float nextFloat;
        do  {
            nextFloat = input.nextFloat();
            balance += nextFloat;
        } while (nextFloat != 0);
    Remember to handle the exceptions that nextFloat() can generate, eg what happens if someone enters "abc"

  4. #4
    Join Date
    Apr 2009
    Posts
    7

    Re: reading input

    Awesome thanks guys, I see what I was doing wrong now your examples work great.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured