|
-
April 11th, 2009, 01:29 AM
#1
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?
-
April 11th, 2009, 04:15 AM
#2
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;
}
-
April 11th, 2009, 05:27 AM
#3
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"
-
April 11th, 2009, 06:39 AM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|