gpt4 book ai didi

java - Scanner.next() 不会停止

转载 作者:行者123 更新时间:2023-12-01 13:22:23 27 4
gpt4 key购买 nike

public class ElectronicCounter {

public ElectronicCounter(User user)throws IOException{
Scanner scanner = new Scanner(System.in);
boolean done = false;
loginName = user.getName();

System.out.println("--------------------------------------------------------");
System.out.println("Welcome to the Electronic-Sales Counter! ");

while(!done){
try{
System.out.print("Please enter '1' to record sales or '2' to exit:");
input = scanner.nextLine();
System.out.println("bug");
if(input=="1"){
System.out.println("Please enter a list of purchasing-product ID and number");
done = true;
}
else if(input=="2"){
System.out.println("<LOG> User " +loginName+ " has successfully logged off! ");
done = true;
}
else{
System.out.println("<LOG> Invalid command");
}
}
catch (NoSuchElementException e){
System.out.println("<LOG> No Such Element");
}
catch (IllegalStateException e){
System.out.println("<LOG> IllegalState");
}
}
scanner.close();
}

static String loginName;
static String input;
}

scanner.nextLine() 时,扫描仪不会停止搜索 token 。被计算出来。我想问如何停止扫描仪等待输入?谢谢

最佳答案

决不使用==比较字符串。当使用 == 比较字符串对象时,您不是在比较它的值,而是在比较它的引用。

始终使用 equals 方法进行比较。

input.equals("2");

关于java - Scanner.next() 不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951760/

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