Java Scanner Issue? [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 6 years ago.
take a look at the following code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
String[] students = new String [numberOfStudents];
//input.nextLine();
for (int i = 0; i < students.length; i++){
System.out.println("Enter name for student " + (i+1) + ":" );
students[i] = input.nextLine();
}
for (int i = 0; i < students.length; i++){
System.out.println(students[i]);
}
}
}
You can see I commented out the statement "input.nextLine();" just before the first loop, and if I execute this code (this was my original code), the loop runs twice and then stops and waits for my input, then continues normally, so in order to fix this I need to put in that commented line and then it works normally, stops after every iteration and asks for input. Why is it like this, how exactly does Scanner work ?
Example output:
Without input.nextLine(); before the loop:
Enter the number of students: 4
Enter name for student 1:
Enter name for student 2:
name1 name2
Enter name for student 3:
name3
Enter name for student 4:
name4
And if I uncomment the input.nextLine(); the output is as follows:
Enter the number of students: 4
Enter name for student 1:
name1
Enter name for student 2:
name2
Enter name for student 3:
name3
Enter name for student 4:
name4
now it executes normally.

In the for loop, you need to replace input.nextLine(); with input.next(); as nextLine() method advances the scanner to next line and returns what was read whereas next() waits for next input. Below would work:
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
String[] students = new String[numberOfStudents];
// input.nextLine();
for (int i = 0; i < students.length; i++) {
System.out.println("Enter name for student " + (i + 1) + ":");
students[i] = input.next();
}
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}

Related

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

Loop->Array Output

I'm writing a loop to fill an array. I think I have the coding down, but when I run the compiled code through Java, it doesn't come out right in the command prompt.
Here's the code:
import java.util.Scanner;
import java.io.*;
public class Pr42
{
public static void main(String[]args) throws IOException
{
int k,m,g;
String n;
//double g;
Scanner input1=new Scanner(System.in);
String[]Name=new String [5];
double[]Grade=new double[Name.length];
k=0;
while (k<Name.length)
{
m=k+1;
System.out.print("Enter the name of student "+m+": ");
Name[k]=input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student "+m+": ");
Grade[k]=input1.nextInt();
k++;
}
}
}
Here's the output in the command prompt:
Enter the name of student 1:
Please enter the grade of student 1:
Please enter the name of student 2: Please enter the grade of student 2:
The problem is that line regarding the second student.
What did I do wrong in the code to get an output like that?
You need to identify name has input in next line with Name[k] = input1.nextLine();
int k, m, g;
String n;
//double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
m = k + 1;
System.out.print("Enter the name of student " + m + ": ");
Name[k] = input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student " + m + ": ");
Grade[k] = input1.nextDouble();
input1.nextLine();
k++;
}
EDITED: As per mentioned in Tom's comment under this answer when you have Name[k] = input1.nextLine(); instead of input1.nextLine(); program works correctly, but it messed up with value of array.
the nextInt of the Scannerdoes not read the "new line" character.
there are 2 ways to fix it.
1. call input1.nextLine(); after the input1.nextInt(); ignore what you get here, it is just to make it go to the next line.
Grade[k] = input1.nextInt();
input1.nextLine();
2. call input1.nextLine(); for the grade.
the String you get you can cast to int and save in Grade[k].
String str = input1.nextLine();
Grade[k] = Integer.parseInt(str);
This works:
public static void main(String[] args) throws IOException {
int k, m, g;
String n;
// double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
m = k + 1;
System.out.print("Enter the name of student " + m + ": ");
Name[k] = input1.nextLine();
System.out.print("Please enter the grade of student " + m + ": ");
Grade[k] = input1.nextInt();
input1.nextLine();
k++;
}
}
I recommend you to please go through this question, you shall have your doubts clarified. Excerpt from the answer given in that post:
Scanner#nextInt method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.
The problem is that: Grade[k] = input1.nextInt(); don't reads the end of line or anything after the number.
Try placing a input1.nextLine(); after Grade[k]=input1.nextInt(); should solve the issue:
while (k<Name.length)
{
m=k+1;
System.out.print("Enter the name of student "+m+": ");
Name[k]=input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student "+m+": ");
Grade[k]=input1.nextInt();
input1.nextLine();
k++;
}

Having trouble getting user input into array without getting errors

I am creating a roommate bill splitter program and do not know what I am doing wrong. It gets hung up after asking what the roommates names are. Output is below code.
package roomBillSplit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Roommate Bill Splitter!\n");
//Get Residence Name from User
System.out.print("Please Enter Name of Place or Address: ");
String place = input.nextLine();
roommates(place);
bills(place);
input.close();
}
public static void roommates(String place) {
int numRoom, i;
Scanner input = new Scanner(System.in);
//Get # of Roommates at Residence
System.out.print("How Many Total People Reside at " + place + ": ");
numRoom = input.nextInt();
String[] roommates = new String[numRoom];
//ArrayList<String> roommates = new ArrayList<String>(5);
//Get Names of Roommates
for(i = 0; i < roommates.length; i++) {
System.out.print("What is Person Number " + (i + 1) + "'s Name: ");
if(input.hasNext()) {
roommates[i] = input.nextLine();
input.next();
}
}
for(i = 0; i < roommates.length; i++) {
System.out.println(roommates[i]);
}
input.close();
}
}
public static void bills(String place) {
int numBills, i;
Scanner input = new Scanner(System.in);
//Get # of Bills Split Between Roommates
System.out.print("What is the Total Number of Bills to be Split at " + place + ": ");
numBills = input.nextInt();
String[] bills = new String[numBills];
//Get Names of Bills
for(i = 0; i < bills.length; i++) {
System.out.print("Please List Bill Number " + (i + 1) + ": ");
if(input.hasNext()) {
bills[i] = input.nextLine();
input.next();
}
}
for(i = 0; i < bills.length; i++) {
System.out.println(bills[i]);
}
int amount[] = new int[numBills];
//Get Amount of Each Bill
for(i = 0; i < bills.length; i++) {
System.out.print("What is the Total Amount of the " + bills[i] + " Bill: $");
if(input.hasNextInt()) {
amount[i] = input.nextInt();
input.next();
}
}
input.close();
for(i = 0; i < amount.length; i++) {
System.out.print(bills[i]);
System.out.print("\t$");
System.out.println(amount[i]);
}
}
}
Output:
Welcome to Roommate Bill Splitter!
Please Enter Name of Place or Address: 1212 Main
How Many Total People Reside at 1212 Main: 2
What is Person Number 1's Name: a
What is Person Number 2's Name: b
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at roomBillSplit.Main.bills(Main.java:62)
at roomBillSplit.Main.main(Main.java:19)
What is the Total Number of Bills to be Split at 1212 Main:
Your program waiting for user input. If you press any key it will resume. This is because
You have extra input.next() in remove that line it will work.
//Get Names of Roommates
for(i = 0; i < roommates.length; i++){
System.out.print("What is Person Number " + (i + 1) + "'s Name: ");
if(input.hasNext()){
roommates[i] = input.nextLine();
input.next();
}
}
UPDATE:
You don't need to use input.hasNext() and input.next() because input.nextLine() will block for the user input.
When you close the Scanner at the end of your roommates method, you also close System.in, so you can't scan from it any more when you need it in your bills method, and that's why your new Scanner there doesn't work.
Pass the Scanner you create in your main method as an argument to your roommates and bills method, instead of having those methods create a new Scanner, and remove all of the input.close() statements except for the one in main.
Edited to add:
It will fix your other problem if you change how you are reading from the scanner inside of your loops to look like this:
...
roommates[i] = input.next();
input.nextLine();
...
bills[i] = input.next();
input.nextLine();
...
amount[i] = input.nextInt();
input.nextLine();
...

Java array to input student names according to their number

I need to create an array that prompts a professor to input how many students are in their class. Then prompts them to input their names until the number of students is met. What I have is clearly wrong but I was hoping for some insight.
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}
EDIT: I changed the code a bit, mainly the array. With the for loop I am intending to simply have it go through each number and assign a student name to it. But with the last line of code it gives me an error saying its a confusing indentation.
EDIT 2: After proofreading my question and the code myself I've noticed very basic mistakes and have dealt with them, but one last question. Right now while the code works, when it asks for me to input the name, it skips student 1, leaves it blank then moves onto student 2. As shown in this screenshot http://puu.sh/8fl8e.png
you weren't far...
Scanner console = new Scanner (System.in);
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.next();
}
to test the code:
for (int i=0; i<studentName.length; i++){
System.out.println(studentName[i]);
}
EDIT: an answer for your second edit:
use
console.next();
instead of
console.nextLine();
I guess that studentName should be String, not double. And maybe you should consider taking advantage of fact that Java is OO? :)
since you are taking names as input which is string type but you are using double(not possible to store string) and you also missed bracket after for loop.
change
double [] studentName = new double [numberOfStudents];
to
String [] studentName = new String [numberOfStudents];
final correct code:
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String[numberOfStudents];
for (int i=0; i< numberOfStudents; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.nextLine();
}
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}

Lost first element in array? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Yes this is an assignment...
I've got 2 arrays; one for student names and one for their scores. I've asked the user to input the number of students to initialize the sizes of both, and then loop through the input process to fill the elements.
But the weirdest thing happens that hasn't happened before. It seems that the student array is cut short by one element when the code is run (after 4 entries the program jumps to the next input loop), but even weirder is that the truncation seems to be at the front of the array, because the scores loop starts with a blank where a name should be but allows for 5 inputs.
import java.util.Scanner;
public class Ex6_17SortStudents {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++)
students[i] = input.nextLine();
scores = new double[numOfStu];
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}
}
Any ideas why this happens?
There's eventually a sort but that's a mess i think i have a handle on.
Sorry if the format for the post is wrong -- first time posting; trying my best.
thanks
This debugging output should give you a clue to your problem:
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
System.out.print("Name index " + i + ": ");
students[i] = input.nextLine();
}
And this answer to this question is exactly the answer you need.
Use students[i] = input.next();
Just checked it, and it works now.
nextLine() advances your scanner past the current line and returns the input that was skipped -- so you were pretty much skipping a line. The first time it enters the loop, you lose an i value, that is i is now 1, yet your scanner does not record user input. The second time around, when i is 1, it takes input, and so forth.
New code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
scores = new double[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
students[i] = input.next();
}
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}

Categories

Resources