I want to read in an operator through user input with a scanner. The scanner should read in the input as long as a pre-defined operator is typed in. I thought it would work like this, but it returns command cannot be resolved in the while part.
String [] operators = new String [3];
operators[0] ="!";
operators[1] ="&&";
operators[2] ="||";
Scanner sc = new Scanner(System.in);
System.out.println("Command: ");
do {
String command = sc.next();
} while(!command.equals(operators[0]) || !command.equals(operators[1]) || !command.equals(operators[2]));
Declare command outside the do-while loop because if you declare any variable inside do-while loop, it's scope will be limited to the body of the do-while loop. It won't be accessible outside the loop's body.
String [] operators = new String [3];
operators[0] ="!";
operators[1] ="&&";
operators[2] ="||";
String command;
Scanner sc = new Scanner(System.in);
System.out.println("Command: ");
do {
command = sc.next();
} while(!command.equals(operators[0]) || !command.equals(operators[1]) || !command.equals(operators[2]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With