loop skipping some statements - java

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.

Related

How do I get the name input to read whitespaces

So im having trouble getting the first read input to read all inputs on the line. But for some reason it doesnt take into consideration of whitespaces. in fact, it considers the whitespace from the print information as part of the whitespace. only name has this problem. ID does not have this problem. I would just like to know how to fix this one problem since it is giving me the most trouble.
public class Project2 {
public static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
PersonList PersonList = new PersonList();
System.out.print("Welcome to my personal Management Program\n\n");
System.out.print("\nChoose one of the following options: \n\n");
//print out options for user
for (;;) {
int input = 0;
System.out.print("1- Enter the information of a faculty\n");
System.out.print("2- Enter the information of a student\n");
System.out.print("3- Print tuition person for a student\n");
System.out.print("4- Print faculty information\n");
System.out.print("5- Enter the information of a staff member\n");
System.out.print("6- Print the information of a staff member\n");
System.out.print("7-Exit the program\n\n");
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
if (input == 1) {
faculty f = new faculty();
System.out.print("Enter the faculty info:\n");
System.out.print("\tName of Faculty: ");
f.name = sc.nextLine();
System.out.print("\tID: ");
f.ID = sc.nextLine();
String rank, department;
for(;;) {
System.out.print("\n\tRank: ");
rank = sc.nextLine();
if (rank.equalsIgnoreCase("professor") || rank.equalsIgnoreCase("adjunct")) {
f.rank = rank;
break;
}
else {
System.out.print("\"" + rank +"\" is invalid");
}
}
for(;;) {
System.out.print("\tDepartment: ");
department = sc.nextLine();
if (department.equalsIgnoreCase("mathematics") || department.equalsIgnoreCase("engineering") || department.equalsIgnoreCase("sciences")) {
f.Department = department;
break;
}
else {
System.out.print("\"" + department +"\" is invalid");
}
}
System.out.println("Faculty added!");
PersonList.addPerson(f);
}
When you read the selection input = sc.nextInt() it returns the next integer it finds, stopping right after that. It returns the choice typed but it does not read the newline. If you typed 1 (space one space) it would skip over the leading space then read the 1 and stop; it would not read the following space or the newline.
So when you get to the faculty name f.name = sc.nextLine() it reads whatever was remaining from the input = line, which is probably just a newline, and returns that for the name.
Now when you get to f.ID = sc.nextLine() the input buffer is clear so it reads ID as you expect it to.
A simple solution is to just finish reading the line by adding a nextLine() after reading the selection:
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
sc.nextLine(); // Read the remainder of the line and throw it away
Read the javadoc for java.util.Scanner and for nextInt() and nextInt(radix)

save several names in a string array [duplicate]

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;
}

Why does my scanner repeat? [duplicate]

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.

Skipped Iteration in For Loop in Java

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.

How do I empty the buffer inside the loop each iteration in Java?

I am writing a for loop to fill an array. This is my code:
for (int i = 0; i < students.length; i++)
{
System.out.println("Student " + (i+1));
System.out.print("First Name: ");
students[i][0] = keyboard.nextLine();
System.out.print("Last Name: ");
students[i][1] = keyboard.nextLine();
System.out.print("Date of Birth (MM/DD/YYYY): ");
students[i][2] = keyboard.nextLine();
}
however when I run it outputs the following:
First Name: Last Name:
and will read only one string for the First Name and Last Name.
This only happens on the first iteration, the following iterations are all fine. I think this might have something to do with emptying the buffer but why does it only happen the first time?
I wonder if you have an end of line character that wasn't dealt with properly before this block of code is called. Do you use any of Scanner's other methods such as nextInt(), nextDouble(), or next()? If so, then you may need to follow these method calls with a call to nextLine() to swallow the end of line token. For e.g.
int myInt = keyboard.nextInt();
keyboard.nextLine(); // call this to swallow end of line character
double myDouble = keyboard.nextDouble();
keyboard.nextLine();

Categories

Resources