Must type multiple times, before scanner reads input

前端 未结 3 570
情话喂你
情话喂你 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 07:00

    Your concepts are wrong here.

    Each time you ask for sc.next() it will wait for the input. If that input is equal to what you want it to be, then the code is executed.

    You can correct this by storing sc.next() in a String variable, and then comparing it.

    Here: if (sc.next().equals("1")) it asks for an input.

    If that input is 1 then the code is executed and --1-- is printed out. Else, it jumps to this: if (sc.next().equals("2")). Now if the input is 2 then the code to print --2-- is executed. Else, it jumps to if (sc.next().equals("3")) and so on.

    You can correct this by:

    • storing sc.next() in a String variable, and then comparing it.
    • using a switch-case block to compare the input.

提交回复
热议问题