scanner.next()不会停止

时间:2014-02-22 08:25:52

标签: java java.util.scanner

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()时,扫描程序不会停止搜索令牌。我想问一下如何阻止扫描仪等待输入?谢谢

1 个答案:

答案 0 :(得分:1)

从不使用==比较字符串。使用==来比较字符串对象时,您不是要比较它的值,而是它的引用。

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

input.equals("2");
相关问题