System.out.print("Input the number of persons: ");
Scanner scanner = new Scanner(System.in);
int noOfP = scanner.nextInt();
Person[] person = new Person[noOfP];
String name;
int age;
for(int i = 0; i < person.length; i++){
System.out.println("Input name for guest: ");
name = scanner.nextLine();
System.out.println("Input age for guest: ");
age = scanner.nextInt();
person[i] = new Person(name,age);
}
I just wanted to initialize the Person array and set the name and age, but it throws an InputMismatchException at line age = scanner.nextInt();
When you ask for the number of persons, the user isn't just typing a number, they're also inserting a line terminator into the input stream. So when you ask for the name, you're not getting the name, you're getting the line terminator just before the name. And then when you do the .nextInt() for the age, you're finally getting the name. So the first thing you need to do is add scanner.nextLine() after you read the value of noOfP to skip that line terminator. That will fix things through the age of the first person. And then things will start breaking again.
You do the same thing when you ask for age: you invoke scanner.nextInt(), leaving another line terminator in the stream. You need another scanner.nextLine() after that so things don't blow up on the second person.
The code will look like this:
System.out.print("Input the number of persons: ");
Scanner scanner = new Scanner(System.in);
int noOfP = scanner.nextInt();
scanner.nextLine();
Person[] person = new Person[noOfP];
String name;
int age;
for(int i = 0; i < person.length; i++){
System.out.println("Input name for guest: ");
name = scanner.nextLine();
System.out.println("Input age for guest: ");
age = scanner.nextInt();
scanner.nextLine();
person[i] = new Person(name,age);
}
When you hit enter after scanner.nextInt(), the ending newline character is never removed. I've always found it easiest to use Integer.parseInt(scanner.nextLine()) instead of scanner.nextInt() for this reason; these problems never occur.
Related
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)
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;
}
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]);
}
I'm rather new to java and I am playing around with scanners. This is my code:
System.out.print("Name? ");
String name = s.nextLine();
System.out.print("Height? ");
double height = s.nextDouble();
System.out.print("Haircolor? ");
String haircolor = s.nextLine();
System.out.print("Age? ");
int age = s.nextInt();
System.out.print("Job? ");
String job = s.nextLine();
As you can probably see, I'm getting input about some person. Now the problem is that it gives an InoutMismatchException when I try to read the double. After reading this thread I changed that line to double height = Double.parseDouble(s.nextLine());. That works but now it doesn't stop after printing "Job? ". The program just goes on without reading anything.
Can anyone maybe tell me why that is? And also why I got this exception? I just suspected that a scanner maybe can't read different types (double, string, int) and can't "switch back" to String after having read an int. But that seems kinda odd.
Thank you so much in advance for an answer.
Tony
try this..
System.out.print("Name? ");
String name = s.nextLine();
System.out.print("Height? ");
double height = s.nextDouble();
s.nextLine();
System.out.print("Haircolor? ");
String haircolor = s.nextLine();
System.out.print("Age? ");
int age = s.nextInt();
s.nextLine();
System.out.print("Job? ");
String job = s.nextLine();
I got the following code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
And the output for that code is the following:
How many names are you going to save:3
Type a name: Type a name: John Doe
Type a name: John Lennon
Notice how it skipped the first name entry?? It skipped it and went straight for the second name entry. I have tried looking what causes this but I don't seem to be able to nail it. I hope someone can help me. Thanks
The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
or just read the line and parse the value as an Integer.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
use sc.nextLine(); two time so that we can read the last line of string
sc.nextLine()
sc.nextLine()
It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.
Here a small change that you can do:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
This because in.nextInt() only receive a int number, doesn't receive a new line. So you input 3 and press "Enter", the end of line is read by in.nextline().
Here is my code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
You could have simply replaced
names[i] = in.nextLine(); with names[i] = in.next();
Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.