DSATH DSATH - 5 months ago 18
Java Question

When I run this code it is not allowing me to input to my scanner. Am I using the Scanner properly?

When I run the code I am not able to input to the scanner and continue through the code the way I want to. Can someone help me with some advice? I have imported the java.util.Scanner succesfully. BTW, I do call the method in the original program, I just removed it before I posted the question. I am using BlueJ.

public class Instructions extends ConsoleProgram
{
public boolean question(String prompt) {
Scanner s = new Scanner(System.in);
println(prompt);
String str = s.next();
boolean result = true;
while(!(str.equals("yes") || str.equals("no"))) {
str = s.next();
println("enter yes or no");
}
if (str.equals("yes")) {
result = true;
} else if (str.equals("no")) {
result = false;
}
return result;
}

Answer

Am I using the Scanner properly?

That isn't the problem. The real problem is a straight-forward bug in your application logic. This condition:

  !(str.equals("yes") && str.equals("no"))

can never be false. A String cannot be both equal to "yes" AND equal to "no" at the same time. Therefore your while loop cannot terminate.


UPDATE

Following the edit, your code should more or less work. But this is not quite right.

while(!(str.equals("yes") || str.equals("no"))) {
    str = s.next();
    println("enter yes or no");
}

1) You are reading the next input token BEFORE you prompt for it.

2) You are not consuming the remaining characters after the first token of the line that the user just entered.

This is better

while(!(str.equals("yes") || str.equals("no"))) {
    s.nextLine();
    println("enter yes or no");
    str = s.next();
}

I suggest you go back and read the javadocs for the Scanner class carefully.

It is also possible that new Scanner(System.in) is wrong. That is normally the right thing to do, but your requirements might require you to read use input from some other input stream.