gpt4 book ai didi

java - 扫描器只允许定义的字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:37 24 4
gpt4 key购买 nike

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

最佳答案

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

关于java - 扫描器只允许定义的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com