Reading Strings next() and nextLine() Java

前端 未结 1 1347
温柔的废话
温柔的废话 2020-12-06 16:07

The problem is I cant read the variable input with next() cause when I try to split (.split\" \") every whitespace then the array just get the first two words I type so I ha

相关标签:
1条回答
  • 2020-12-06 16:20

    Put keyboard.nextLine() after this line:

    int answer=keyboard.nextInt();
    

    This is a common problem that usually happens when you use nextLine() method after nextInt() method of Scanner class.

    What actually happens is that when the user enters an integer at int answer = keyboard.nextInt();, the scanner will take the digits only and leave the new-line character \n. So you need to do a trick by calling keyboard.nextLine(); just to discard that new-line character and then you can call String input = keyboard.nextLine(); without any problem.

    0 讨论(0)
提交回复
热议问题