hamc17 hamc17 - 1 year ago 130
Java Question

Java: Input comparison

I'm wondering why when I type 'y' after being asked if there are any more digits in this method the code works correctly and leaves the loop, but upon typing 'n' and hitting return, I need to type 'n' and hit return again or the process just hangs.

Why?

The string 'input' is being passed from the user's input in the main method and is in this case "addition".

private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{

while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}


I've managed to get the code working by using

System.out.println("Any more digits? Type y/n");
String yayOrNay = scan.next();
if (yayOrNay.length()==1 && yayOrNay.charAt(0)=='y')
{
keepGoing = true;
}


but that seems a little too complicated to me for all that it's doing.

Answer Source

scan.next() pulls a new character from the input steam.

So when you check for 'n' and scan.next().matches("Y|y") executes, it is actually skipping 'n' for your next comparison.

The solution is to assign scan.next() into a variable you can use:

        while (keepGoing == true)
        {
            System.out.println("Next digit = (Type the digit)");
            additionValue = additionValue + scan.nextInt();
            System.out.println("Any more digits? Type y/n");
            String next = scan.next();
            if (next.matches("Y|y"))
            {
                keepGoing = true;
            }
            else if (next.matches("N|n"))
            {
                keepGoing = false;
            }
            else
            {
                System.out.println("Great, you broke it.");
                System.exit(1);
            }
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download