Why is Scanner skipping inputs from the user - java

I have a small task that allows the user to enter the regions and their neighbors of any country.
I did everything and I just have a small problem which is when I run my code and the program asks the user to enter the number of regions, if the user enters 13 or and number greater than 10, the system will consider that number is like two inputs and it will not allow the user to enter anything for the second question and it will prompt him with the third question immediately. Why?
I think the problem with the Scanner class in the following command:
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
region = new CountryRegion[REGION_COUNT];
String[] neighbours;
for (int r = 0; r < region.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1) + ": ");
String regionName = kb.nextLine();
System.out.print("How many neighbors for region #" + (r + 1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
neighbours = new String[size];
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #" + (n + 1) + ": ");
neighbours [n] = kb.nextLine();
}
region [r] = new CountryRegion(regionName, neighbours);
}
else
System.exit(0);
}
for (int i = 0; i < REGION_COUNT; i++) {
System.out.print(region[i].getRegionName() +": ");
for (int k = 0; k < region[i].getRegionAjesint().length; k++) {
System.out.print(region[i].getRegionAjesint()[k] +", ");
}
System.out.println();
}
mapColor = new MapColor(region);
Any help, please?

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().

Related

java.lang.NumberFormatException error after inputting a number [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am feeling quite stupid at this point for not being able to figure out something that is most likely a simple fix. I keep getting the error "Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at searchSorting.main(searchSorting.java:15)" after inputting how many numbers I want to input. Others solutions to this problem just don't seem to apply to me somehow. Thanks for the help
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
int number, search, item, array[], first, last, middle;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
item = Integer.parseInt(in.nextLine());
double[] values = new double[item];
for (int i = 0; i < values.length; i++) {
System.out.print("Input number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
for (int index = 0; index < 5; index++)
System.out.print(values[index] + " ");
in.nextLine();
Arrays.sort(values);
System.out.println("Sorted number is: " + Arrays.toString(values));
System.out.println("Enter the number you are looking for?");
search = in.nextInt();
first = 0;
last = (item - 1);
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}}
For more info check out Scanner and Integer documentation, it's an excellent resource.
Edit: Try removing line 15 and replacing item with number in the next line
You call this:
number = in.nextInt();
Assuming the user types 123 and ENTER, this call consumes the 123 and leaves the input stream positioned before the end-of-line character.
The next relevant code is
item = Integer.parseInt(in.nextLine());
The nextLine call advances the input stream past the end-of-line, returning all characters it passed on the way. Since the ENTER key was pressed immediately after 123, the returned value is the emoty string. Which is not an integer.
You need to review your strategy of sometimes scanning numbers (nextInt) and sometimes scanning rest-of-linr (nextLine). Mixing the two needs to be done quite carefully. You might be better advised to stick to the numerical methods (nextInt/nextDouble).
For example, replacing this
item = Integer.parseInt(in.nextLine());
by this
item = in.nextInt();
automatically handles the line-ending.
From discussion in comments:
I am still confused as to why it's having me input
the value a second time on the next line
Making assumptions about how you modified the code since your initial question: it's because you've written code that reads the number twice:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt(); // **** first input ****
array = new int [number];
item = in.nextDouble(); // **** second input ****
double[] values = new double[item];
Each time you call for in.nextSomething() the Scanner is going to read more input. It should likely just be this:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
double[] values = new double[number];

For loop to get user input lets you enter two values for the first question, but only calculates one value

I created a small program that asks the user for 10 random numbers and it will print the sum of those numbers. I embedded it with a for loop and included a counter. Everything seems to be working fine except when I run the program, the first question allows me to enter two values, but it will still only calculate a total of 10 numbers.
Below is what I currently have and I need to understand what is going wrong when it prompts the user for the number the first time:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
sum += numberInput;
} else {
System.out.println("Invalid Number");
}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
}
}
In each loop, you're calling scanner.nextInt() and scanner.hasNextInt(). But you do not use the result of hasNextInt() in a meaningful way (you might have noticed that your "Invalid Number" output is not what happens if you enter something that's not a number).
The first call to nextInt() blocks until you enter a number. Then hasNextInt() will block again because the number has already been read, and you're asking whether there will be a new one. This next number is read from System.in, but you're not actually using it in this iteration (you merely asked whether it's there). Then in the next iterations, nextInt() will not block because the scanner already pulled a number from System.in and can return it immediately, so all the subsequent prompts you see actually wait for input on hasNextInt().
This amounts to 11 total input events: The firts nextInt() plus all 10 hasNextInt()s
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
// boolean hasNextInt = scanner.hasNextInt();
//if (hasNextInt) {
sum += numberInput;
// } else {
// System.out.println("Invalid Number");
//}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
Don't call hasnextInt() it has no use here.
It has taken 11 inputs rather than 10.
If you remove this condition it will take 10 inputs and work fine.
Your condition have no impact on it.

Why is my for loop executing more than once for each time a value is inputted?

I have a programming assignment that's asking me to have the user input 10 (or less) integers and put them in an array, then take the average of them and output it. If they input a period, the program should stop asking for integers and do the averaging.
My problem is that whenever the user inputs an integer, the for loop executes more than once.
My code is below. Any ideas on how to fix this?
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(entered = 0; entered < 10; entered++){
System.out.println("Please enter an integer: ");
int input = br.read();
if(input == '.') break;
else{
intArr[entered] = input;
}
}
int total = 0;
for(int i : intArr){
total += i;
}
System.out.println("Average: " + total/entered);
System.out.println("Entered: " + entered);
Use String input = br.readLine() to read an entire line.
To check for ".", use if (input.equals(".")) { ... }.
(check out this if you want to know why you have to use .equals() instead of == for Strings)
Finally, to convert the input to an integer, see here.
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String str = br.readLine();
if (".".equals(str)) {
break;
}
int input = Integer.valueOf(str);
intArr[entered] = input;
}
Ok Its Really Simple
First let Me Explain You Why Its Happening
Ok the read() function reads first char of the input value and rest of line is stored in buffer
so when you enter any integer
for example: 1
1 is stored in variable and '\n'which java by defaults adds to a input value gets stored in buffer
so in next iteration of loop
it reads the char '\n' from buffer as input value and moves to next iteration
EXAMPLE 2:
If In Your Program We Enter Input As 12
It Skips Two Iterations
Coz Firstly It Stores 1 At The Time Of Input
In Next Iteration It Takes value 2 of previous input as input for this time
In Further Next Iteration It Takes '\n'
and then moves to next iteration at which their is no character left in memory so it asks you to input
Note:::
read() functions return character so even if user enters 5 while calculation ASCII Code Of 10 will be used that is 53 not one creating problems
FIX:::
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String input = br.readLine();
if (input.equals(".")) {
break;
} else {
intArr[entered] = Integer.parseInt(input);
}
}
int total = 0;
for (int i: intArr) {
total += i;
}
System.out.println("Average: " + total / entered);
System.out.println("Entered: " + entered);

Why my program in not exiting out of while loop?

Code:
int size=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter size of the Graph");
size = in.nextInt();
System.out.println(size);
for (int i = 1; i <= size; i++) {
Scanner in2 =new Scanner(System.in);
while(in2.hasNextInt()){
int num = in2.nextInt();
System.out.print("(" + i + "," + num + ")"+",");
System.out.println();
}
System.out.println("out of the while loop");
}
Input & Output:
Enter size of the Graph
4
4
2 3 4
(1,2),
(1,3),
(1,4),
2 5 6
(1,2),
(1,5),
(1,6),
As you can see my program doesn't exists while loop. It still prints the value for i=1.
What I am doing wrong?
Your program is constantly waiting for a new feed, in order to terminate it - you should indicate the input was ended (or provide a non int input).
To indicate the feed ended - you should provide EOF - which is ctrl+D in linux and ctrl+Z in windows.
int num = in2.nextInt();
try adding in2.nextLine(); after that.
Note:
You shouldn't be doing new Scanner(System.in); multiple times.
Scanner in2 = new Scanner(System.in); // this is useless just use in

Java Scanner not accepting input after the For loop

I am currently working on a program that requests input for the names and scores of two teams. When I request input for the name and 9 scores of the first team, the scanner accepts input just fine. However, after the for loop, the scanner does not accept input for the name of the second team. This is not the entire program, but I have included all the code up until the point where it is giving me trouble. I suspect that it may have something to do with the for loop because team2 accepts user input just fine when I place it before the for loop.
import java.util.Scanner;
public class sportsGame{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String team1;
String team2;
int team1Scores[] = new int[9]
int team1Total = 0;
int team2Scores[] = new int[9];
int team2Total = 0;
System.out.print("Pick a name for the first team: ");
team1 = input.nextLine();
System.out.print("Enter a score for each of the 9 innings for the "
+ team1 + " separated by spaces: ");
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
System.out.print("Pick a name for the second team: ");
team2 = input.nextLine();
}
}
Scanner's nextInt method does not skip a line, only fetches the int. So when the first loop ends, there is still one newline character left and your input.nextLine() returns a blank string. add a input.nextLine() after your loop to skip this blank line and to solve your problem like this:
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
input.nextLine();
//rest of your code

Categories