Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - scanner only allow defined strings

Tags:

java

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]));
like image 756
JacobBalb Avatar asked Nov 30 '25 05:11

JacobBalb


1 Answers

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]));
like image 67
Yousaf Avatar answered Dec 01 '25 20:12

Yousaf