java-scanner只允许定义的字符串
我想通过扫描仪的用户输入读取操作员。只要输入了预定义的运算符,扫描仪就应该读取输入。我原以为它会这样工作,但它返回while部分中无法解析的java-scanner只允许定义的字符串,java,Java,我想通过扫描仪的用户输入读取操作员。只要输入了预定义的运算符,扫描仪就应该读取输入。我原以为它会这样工作,但它返回while部分中无法解析的命令 String [] operators = new String [3]; operators[0] ="!"; operators[1] ="&&"; operators[2] ="||"; Scanner sc = new Scanner(System.in); System.out.println("Comman
命令
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]));
在do while
循环外部声明command
,因为如果在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]));
命令
在while
块的范围内声明,并在其外部求值。另外,对于sc.next()
的值,您的while
语句的计算结果会是false吗?我误解了您的问题,因为“returns”一词。这里的代码不会“返回”任何内容。相反,更正确的说法是出现了编译器错误。我希望这有助于您学习一些术语,以便将来可以更清楚地提问。您能告诉我为什么不继续像这样运行代码,但当我在while部分使用exclusive或时?就像这样,它一直在读in@JacobBalb您需要使用&&
运算符而不是|
运算符。