输入字符串检查

时间:2013-05-05 20:44:11

标签: java

我正在编写一个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声明,它仍然会向前跳过。任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:6)

在Java中,我们将字符串与String#equals进行比较。

我不会在equals==之间写下区别,google了解更多信息。你将获得大约100个结果。

答案 1 :(得分:1)

最好在代码中使用if(choice.equals("D"))。您无法将字符串与==进行比较,因为您只是检查内存而不是实际内容。

答案 2 :(得分:0)

而不是在比较部分中使用String:

else if(choice == "C"){
                currentCustomer.checkBalance();
            }

你可以使用字符比较

else if(choice[0] == 'C'){
                currentCustomer.checkBalance();
            }

答案 3 :(得分:0)

您不应该使用==运算符来比较字符串,而是使用String equals方法。操作员检查两个字符串是否存储在内存中的同一位置,而方法检查它们是否具有相同的内容。

如果您使用的是Java 7,则可能需要使用switch语句切换if-elseif-then块。 Java 7引入了在switch语句中使用字符串的能力。

相关问题