我想通过使用扫描仪的用户输入来读取操作员。只要输入了预定义的运算符,扫描程序就应该读入输入。我以为它可以这样工作,但是它在while部分返回command cannot be resolved
。
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]));
最佳答案
在command
循环外声明do-while
,因为如果在do-while
循环内声明任何变量,则其范围将限于do-while
循环的主体。在循环体外无法访问它。
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]));