java - scanner仅允许定义的字符串

时间:2017-10-29 15:02:44

标签: java

我想通过扫描仪的用户输入读取操作员。只要输入了预定义的运算符,扫描仪就应该读入输入。我认为它会像这样工作,但它会在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]));

1 个答案:

答案 0 :(得分:4)

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]));