我正在编写一个 ATM 程序,当用户输入其中一个字符串值时,程序应该检查它并相应地执行一种方法。问题代码在这里:
System.out.println("PRESS");
System.out.println("(D)eposit");
System.out.println("(W)ithdraw");
System.out.println("(C)heck Account Balance");
System.out.println("(Q)uit");
System.out.println("Enter Choice: ");
String choice = scanner.nextLine();
scanner.nextLine();
if(choice == "D"){
currentCustomer.deposit();
}
else if(choice == "W"){
currentCustomer.withdraw();
}
else if(choice == "C"){
currentCustomer.checkBalance();
}
else if(choice == "Q"){
currentCustomer.quit();
}
else{
System.out.println("Invalid choice please reenter: ");
}
如果用户输入“D”,程序将跳至 else 语句。我知道使用 .nextLine
时由于返回字符,您必须使用两个,但我不确定这种情况是否属实。不管怎样,如果我有多余的 .nextLine
无论是否声明,它仍然会向前跳过。任何帮助将不胜感激!
最佳答案
在 Java 中,我们将字符串与 String#equals 进行比较.
我不会写equals
和==
之间的区别,google了解更多信息。您将获得大约 100 个结果。
关于java - 输入字符串检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388970/