Why is Scanner skipping inputs from the user

三世轮回 提交于 2019-12-01 23:03:13

Ok, Very simple your problem is that you are using the nextInt() method of the Scanner class and then using the nextLine() method both of these use the same buffer and here is what's happening.

When you enter the number your asking (let say 10) in the key board your actually entering

10 and the enter key (new line character (\n))

The nextInt() method from the Scanner class will read the 10 and just the 10 that meaning that the new line character (\n) is still in the keyboard buffer and next in your code you have a nextLine() which will read everything up to a new line (\n), which you already have in the buffer!!!

So the way this is all working is that the nextLine() method considers the new line character (\n) left in the buffer as it's input and there for continues to the next iteration of the loop.

The solution to your problem is to clear the buffer of the new line character (\n) you can achieve this by calling a nextLine() method before the actual one in your code like so:

...
int REGION_COUNT = kb.nextInt();
region = new CountryRegion[REGION_COUNT]; 
String[] neighbours;
kb.nextLine(); //CLEAR THE KEYBOARD BUFFER
for (int r = 0; r < region.length; r++) {
     System.out.print("Please enter the name of region #" + (r + 1) + ": ");
     String regionName  = kb.nextLine();
...

This way the nextLine() called extracts the new line character from the buffer, clearing it, and since it doesn't store it it gets discarded leaving you with a new line character free buffer ready to receive full input from the user in your nextLine() method.

Hope this helps.

Sounds like each key press is an input.

You are using nextLine() to get the String but I think you should be using next().

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