Must type multiple times, before scanner reads input

前端 未结 3 569
情话喂你
情话喂你 2020-12-12 06:14

If I run this code

Scanner sc = new Scanner();
while (true) {
        if (sc.next().equals(\"1\"))
            System.out.println(\"--1--\");

        else i         


        
3条回答
  •  情话喂你
    2020-12-12 06:52

    You're calling sc.next() multiple times - so if the input isn't 1, it's going to wait for more input to see whether the next input is 2, etc. Each call to sc.next() will wait for more input. It doesn't have any idea of "that isn't the input you were looking for, so I'll return the same value next time you call".

    Use a local variable to store the result of sc.next()

    while (true) {
        String next = sc.next();
        if (next.equals("1"))
            System.out.println("--1--");
        else if (next.equals("2"))
            System.out.println("--2--");
        else if (next.equals("3"))
            System.out.println("--3--");
        else if (next.equals("4"))
            System.out.println("--4--");
        else if (next.equals("help"))
            System.out.println("--help--");
    }
    

    Also consider using a switch statement instead...

提交回复
热议问题