Java Scanner why is nextLine() in my code being skipped? [duplicate]

谁说我不能喝 提交于 2019-11-28 09:40:31

问题


This question already has an answer here:

  • Scanner is skipping nextLine() after using next() or nextFoo()? 16 answers
    Scanner kb = new Scanner(System.in);
    System.out.println("Inserting L");
    int L = kb.nextInt();   
    System.out.println("Inserting N");
    int N = kb.nextInt();
    System.out.println("Inserting x");
    String x = kb.nextLine();
    System.out.println(x);
    System.out.println("You inputed L,N,x");

Why is there no prompt for nextLine() in this code?


回答1:


Use:

String x = kb.next();

instead of kb.nextLine().

This is because nextInt() reads just the number, not the end of line or anything after the number. When you call nextLine() it reads the remainder of the same line and does not wait for input.

Ideally you should call kb.nextLine() the line after your code for nextInt() to ignore the rest of the line.




回答2:


Scanner kb = new Scanner(System.in);
    System.out.println("Inserting L");
    int L = kb.nextInt();   
    System.out.println("Inserting N");
    int N = kb.nextInt();
    System.out.println("Inserting x");
    String x = kb.next();
    System.out.println(x);
    System.out.println("You inputed L,N,x");

try this one...



来源:https://stackoverflow.com/questions/6289765/java-scanner-why-is-nextline-in-my-code-being-skipped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!