Click to See Complete Forum and Search --> : weird looping issue.


Plan 9
May 27th, 2002, 08:07 PM
I need to print five options, collect a keystroke, and return the right amount if the user intered 1 through 5.
So far it works, But if they press anything else it needs to reprint the menu and select again.
Since there is no goto I was tring to loop while not one of the correct choices.

Heres the weird part. If you select the wrong answer, it will print the menu three times, then wait for your response.
I've been screwing with this all day, and it allways prints three times after a wrong answer.

If anyone can help sort through this, it would be great. This is how we learn. :)

public class Investment3
{
public static void main(String arguments[]) throws Exception
{
Investment3 in = new Investment3();
char amountC, yearC;
int amountI, yearI;
amountI = in.menuAmount();
System.out.println("amount = " + amountI);
}
private int menuAmount() throws Exception
{

int invAmount = 0, ctr = 0;
KeyboardIO kb1 = new KeyboardIO();
while (ctr < 2)
{
char amnt = '0';
System.out.println(" 1 - $1,000");
System.out.println(" 2 - $2,000");
System.out.println(" 3 - $3,000");
System.out.println(" 4 - $4,000");
System.out.println(" 5 - $5,000");
amnt = kb1.readChar();


switch(amnt)
{
case '1':
invAmount = 1000;
ctr = 2;
break;
case '2':
invAmount = 2000;
ctr = 2;
break;
case '3':
invAmount = 3000;
ctr = 2;
break;
case '4':
invAmount = 4000;
ctr = 2;
break;
case '5':
invAmount = 5000;
ctr = 2;
break;
default:
invAmount = 0;
ctr = 1;
}
}
return invAmount;
}

}

Timo Hahn
May 28th, 2002, 04:45 AM
I don't know what your class KeyboardIO does, but i assume that it reads characters from the keyboard till you hit return. In this case whenever you enter a incorrect number (like 6) you end up with the 6 and the return in the buffer you read from. Depending of the system you use the return will be converted in one or two codes (carriage return and/or linefeed). As a result your while loop gets executed more then once!
To avoid this behavior you should read all characters available from the keyboard

while (kb1.ready())
kb1.read();


Hope this helps

Timo

Plan 9
May 28th, 2002, 05:39 AM
I got it cleared up.
Here is my keyboard class.

public class KeyboardIO
{
private char key;

public char readChar() throws Exception
{
key = (char)System.in.read();
System.in.read();
System.in.read();
return key;
}
}

I had to add the two System.in.read(); that don't do anything to catch the extra info.