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