Skipped Iteration in For Loop in Java - 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.

Related

Trying to get the length of a sentence from a user input but it stops after the first word and space

The Java task is to have the user type a sentence/phrase and then print out how many characters the sentence has. My .length() method is only counting the first word and space as characters. I've read previous questions and answers involving nextLine() but if I use that instead of next() it only lets the user type it's question and waits, doesn't print anything else immediately anymore. I'm brand new to Java and I think this can be fixed with a delimiter but I'm not sure how or what I'm missing. TIA!!
Update: Here's my code.
import java.util.Scanner;
class StringStuff{
public static void main( String [] args){
Scanner keyboard = new Scanner(System.in);
int number;
System.out.print("Welcome! Please enter a phrase or sentence: ");
System.out.println();
String sentence = keyboard.next();
System.out.println();
int sentenceLength = keyboard.next().length();
System.out.println("Your sentence has " + sentenceLength + " characters.");
System.out.println("The first character of your sentence is " + sentence.substring(0,1) + ".");
System.out.println("The index of the first space is " + sentence.indexOf(" ") + ".");
}
}
when I type "Hello world." as the sentence it prints:
Your sentence has 6 characters.
The first character of your sentence is H.
The index of the first space is -1.
keyboard.next call is waiting for user input. You're calling it twice, so your program expects the user to enter two words.
So, when you type in "Hello world." it reads "Hello" and "world." separately:
//Here, the sentence is "Hello"
String sentence = keyboard.next();
System.out.println();
//Here, keyboard.next() returns "World."
int sentenceLength = keyboard.next().length();
And when you use nextLine your code is waiting for the user to enter two lines.
To fix this you need to:
Read the whole line with nextLine.
Use sentence instead of requesting user input the second time.
Something like this should work:
String sentence = keyboard.nextLine();
System.out.println();
int sentenceLength = sentence.length();
import java.util.Scanner;
public Stringcount
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter the sentence:");
String str=s.nextLine();
int count = 0;
System.out.println("The entered string is: "+str);
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) != ' ')
count++;
}
System.out.println("Total number of characters in the string: " + count);
System.out.println("The first character of your sentence is " + str.substring(0,1) + ".");
System.out.println("The index of the first space is " + str.indexOf(" ") + ".");
}
}

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

How to pause "for" in Java so that I can input some text

I need to solve a problem when take an input of integer which are the number of lines the user wants to input just next to this input(some sentences) as understandable from text as follows:
The first line of input contains a single integer N, indicating the
number of lines in the input. This is followed by N lines of input
text.
I wrote the following code:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String lines[] = new String[n];
for(int i = 0; i < n; i++){
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
}
And an interaction with the program:
5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
What's the problem? I can't input 0th line.
Suggest a better method to input n numbers of lines where n is user provided to a string array.
The call to nextInt() is leaving the newline for the 0th call to nextLine() to consume.
Another way to do it would be to consistently use nextLine() and parse the number of lines out of the input string.
Start paying attention to style and code formatting. It promotes readability and understanding.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String lines[] = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
I don't know what you would consider better:
Try changing
System.out.println("Enter " + i + "th line");
to
System.out.print("Enter " + i + "th line:");
Makes it look better.
A better way of inputting lines would be to keep reading input lines until you see a special termination char.
Use an ArrayList to store the lines then you don't need to declare the size beforehand

loop skipping some statements

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.

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