This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I'm trying to make a GPA calculator but early on in the code I started having issues; here's the code segment:
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
}
it all goes well until the "Enter grade (include + or -) " part, it repeats twice, so when I compile and get to that part it says "Enter grade (include + or -) Enter grade (include + or -) " before I can type in anything. How can I fix this repeating issue? Because I think it also takes the spot of one grade.
You can fix this by adding
input.nextLine();
after
int length = input.nextInt();
This will make sure that the end of the line that contained that integer is consumed before you try to read more input.
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
}
Further explanation:
Calling input.nextInt() attempts to read a single token from the standard input and convert it to an int. After you type that integer and hit enter, the input stream still contains the end of line character[s], which haven't been read by input.nextInt(). Therefore, the first time you call input.nextLine(), it reads those characters and then discards them (since input.nextLine() strips newline characters), and you end up getting an empty String. That empty String is assigned to gradesArray[0], and the loop proceeds immediately to the next iteration. Adding an input.nextLine() before the loop solves the problem.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I don't know why, but the below code makes the user run the code again, whether they choose to or not. I've tried many things, but it doesn't work correctly.
Thanks!
public static void main (String [ ] args)
{
boolean a = true;
while (a)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
int x = scan.nextInt();
System.out.print("\n\nEnter a second integer: ");
int z = scan.nextInt();
System.out.println();
System.out.println();
binaryConvert1(x, z);
System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\".");
System.out.print("Enter your response here: ");
String RUN = scan.nextLine();
String run = RUN.toLowerCase();
if (run.equals("n"))
{
a = false;
}
System.out.println();
System.out.println();
}
System.out.println("Goodbye.");
}
Scanner.nextInt() doesn't consume the line ending characters from the buffer, which is why when you read the value of the "yes/no" question with scan.nextLine(), you'll receive an empty string instead of the value the user entered.
A simple way to fix this is to explicitly parse the integer from raw lines using Integer.parseInt():
System.out.print("Enter an integer: ");
int x = Integer.parseInt(scan.nextLine());
System.out.print("\n\nEnter a second integer: ");
int z = Integer.parseInt(scan.nextLine());
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
Im currently in the process of creating a program and stores data and I'm running into an issue where its printing out a statement twice and counting it as two in an array(its hard to explain so ill show it)
So this is the code
public static void GetData()
{
Scanner input = new Scanner(System.in);
System.out.println("How many names do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
for (int i = 0 ; i < array.length ; i++ )
{
String[] names = new String[num];
System.out.println("enter employee's name: ");
names[i] = input.nextLine();
}
for(int j = 0; j < array.length;j++)
{
double[] payrate = new double[num];
System.out.println("enter employee's payrate: ");
payrate[j] = input.nextDouble();
}
}
}
the problems is its printing out :
How many names do you want to enter?
4
enter employee's name:
enter employee's name:
harry
enter employee's name:
larry
enter employee's name:
mary
enter employee's payrate:
twice right away so when the user declares let says the array size of 4 it'll print that twice and it'll count that as two spots already so now it only counts 3 of the data and switches to the next array, I'm honestly not sure whats causing this, I tried to debug it but it tells me nothing, any help would be loved!
The first names[i] = input.nextLine(); will read the \n from the line containing the number which you read with input.nextInt(), so you'll get an empty name there.
You could read the num as follows:
String strNum = input.nextLine();
int num = Integer.parseInt(strNum);
I have written this code to let a clink recognize their records
public static void main (String args[]){//Start main
String [] name = new String [5];
int [] age = new int [5];
char [] test = new char [5];
addPatients( name , age , test );
}
public static void addPatients ( String[] n ,int[] a ,char[] t ){
i=0;
while (i<n.length )
{
System.out.println("Enter Patient’s Name: ");
n[i] = scan.nextLine();
System.out.println("Enter Patient’s Age: ");
a[i]=scan.nextInt();
System.out.println("Enter Patient’s Medical test: ");
t[i]=scan.next().charAt(0);
i++;
}
System.out.println("Enter the patient’s index to find his/her information : ");
int index= scan.nextInt();
System.out.println ("Patient name : " + n[index] +"\n Patient age : " + a[index] +"\n Patient Medical test: " + t[index]);
}
but the problem is in the addPatients, when the method start working, it only read the first statement
System.out.println("Enter Patient’s Name: ");
n[i] = scan.nextLine();
from user once and skip it in the second loop!
I appreciate the great explanation that were given so far.....
So the final modified code to correct this problem is here ...
public static void addPatients ( String[] n ,int[] a ,char[] t )
{
final Scanner scanner = new Scanner(System.in);
int i=0;
while (i<n.length )
{
System.out.println("Enter Patient’s Name: ");
n[i] = scanner.nextLine();
System.out.println("Enter Patient’s Age: ");
a[i]=scanner.nextInt();
System.out.println("Enter Patient’s Medical test: ");
t[i]=scanner.next().charAt(0);
i++;
scanner.nextLine(); // To swallow the extra excess newline(enter) character.
}
System.out.println("Enter the patient’s index to find his/her information : ");
final int index= scanner.nextInt();
System.out.println ("Patient name : " + n[index] +"\n Patient age : " + a[index] +"\n Patient Medical test: " + t[index]);
}
Don't use nextLine after nextInt, as nextInt doesn't consume \n and it'll be consumed in nextLine causing it to "skip" your actual input.
One solution is to add additional nextLine after nextInt to "swallow" the \n that wasn't read via nextInt.
So what's happening now in your code is that when you ask for the int input, the user types for example 12 and hit enter (\n), the int value will be read, but when you reach n[i] = scan.nextLine(); again, the \n is waiting to be read.. And it'll be read, so you'll think that it was skipped.
The problem is that when you write scan.next() to read the patient's medical test, the characters that make up the next word are pulled from the scanner, but the newline character or other whitespace that follows them is not.
For example, if the user has typed P A S S then pressed Enter, the letters P A S and S are read from the scanner, but the newline character remains on the scanner - it will be the next character read. Then, on the second iteration of the loop, the following call to scan.nextLine() just reads that left-over newline character, instead of reading the second patient's name.
After that, everything is out of whack. The scanner has several characters that haven't been read yet, but should have been.
The solution to this is to add an extra scan.nextLine() after t[i]=scan.next().charAt(0);, to pull that extra newline character off the scanner.
System.out.println("Enter Patient’s Name: ");
n[i] = scan.nextLine();
System.out.println("Enter Patient’s Age: ");
a[i]=scan.nextInt();
System.out.println("Enter Patient’s Medical test: ");
t[i]=scan.next().charAt(0);
i++;
In the above code, you first enter a name and press enter. The name will be stored in n[i] but the newline(enter) is still there as an input waiting to be read. In your age question, you are waiting for an integer, which skips the new line (could be any number of new lines) and waits for the next integer that you input. The next question for Test result waits for the next token . The next() method ignores all new line characters and spaces till it can fetch a complete token. You enter a value here and hit enter. Now this enter is read by your name question as an input in the second run of the loop, as nextLine() does not ignore newlines. So, you can either ignore the newline you hit after your third question by fetching it after every loop. Or you use next() in place of newLine(). By using next(), you can only enter 1 word though.
My for loop skips to the 2nd grade to be entered and I cannot figure out why this is happening. The output looks like this:
Type in Grade Number 1: Type in Grade Number 2:
public static void main(String args[]){
Scanner inputReader = new Scanner(System.in);
System.out.print("Would you like to input grades?: ");
String input = inputReader.next();
if (input.equals("y")){
String[] grades =new String[2];
for (int counter = 0; counter < grades.length; counter++){
System.out.print("Type in Grade Number " + (counter + 1) + ": ");
grades[counter] = inputReader.nextLine();
}
}
}
next() reads a word, not the whole line, and it doesn't throw away the line after that word so when you type the firstname, the Scanner is still waiting for a reason to consume the rest of the line. Only when you call nextLine() for the first time it does that (I am assuming the rest of the line is blank)
Change your code to be
String lastName = inputReader.nextLine(); // read the whole line, not just a word
System.out.print("Student First Name: ");
String firstName = inputReader.nextLine();
After
String firstName = inputReader.next();
You must call nextLine(). Indeed, next() doesn't consume the EOL, and thus when you call nextLine() in the first iteration of the loop, it immediately consumes the EOL after the first name.