We all know that using method input.nextLine() will allow spaces for the string while running the program, but.. When I use this method inside a loop the run skips the statement. Can anyone please explain why?
I'm trying it with menu:
Code:
do {
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 4:
System.out.println("Please give the full information of the project ");
System.out.print("Project code: "); int code = input.nextInt();
System.out.print("Project Title: "); String title = input.nextLine();
System.out.print("Project Bonus in Percent: "); double bip = input.nextDouble();
Project proj4 = new Project(code4,title4,bip4);
System.out.print("Employee ID you're adding project to: "); String id4=input.next();
ers.addProjectToEmployee(id4,proj4);
break;
/* more cases */
}
} while (choice !=13);
Check statement 3 in case 4.
Here's what happened while running the program:
Enter your choice: 4
Please give the full information about the project
Project code: 66677
Project Title: Project Bonus in Percent:
input.nextInt() does not read the end-of-line, so that' why the effect that .nextLine() is being escaped, while actually that .nextLine() is reading the end-of-line left unread in the input-stream by the .nextInt(). You need an extra .nextLine() after .nextInt().
Update:
Do the following:
System.out.print("Project code: "); int code = input.nextInt();
input.nextLine(); // this is what you need to add
System.out.print("Project Title: "); String title = input.nextLine();
Related
I'm working on a project and I already finished it, I have really simple problem which makes me really confused. I'm trying to ask a user to enter a number from a menu and depending on that different things happen, but I get input mismatch exception whenever I type space in between words. I get that error on the last line of the code, please check my code below, Thanks.
System.out.println("Enter: " + "\n1.Enter Name" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
if(userChoice == 1) {
System.out.println("Enter name");
String name = kb.next();
}
if(userChoice == 2) {
System.out.println("Enter anohter name");
String anotherName = kb.next();
}
if(userChoice == 3)
break;
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
The issue is with your usage of Scanner#next(), in combination with wanting to input multiple "words" sepearted by a whitespace for example. (Disclaimer: I understand your question in the way that you want to enter multiple words for the "name" input, this answer takes that as a prerequisite)
See following excerpt from the Scanner#next() Javadoc:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter for the Scanner is a whitespace. So when you request a name from the user, and the user wants to enter "John Doe", only "John" will be read, and "Doe" will be left, most likely causing the error you are seeing.
The workaround I would propose is to use nextLine() to read the whole line while providing each input line by line.
However, be aware of this issue: Scanner is skipping nextLine() after using next() or nextFoo()?
Keeping that in mind, I would modify your code as follows:
String name = "";
String anotherName = "";
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
kb.nextLine(); // consumes the newline character from the input
if(userChoice == 1) {
System.out.println("Enter name");
name = kb.nextLine(); // reads the complete line
// do something with name
} else if (userChoice == 2) {
System.out.println("Enter another name");
anotherName = kb.nextLine(); // reads the complete line
// do something with anotherName
}
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
Sidenotes:
I moved the declaration of your name and anotherName variables, as they don't have to be re-declared everytime.
However you should actually do something with them (e.g. save them in a list, or create some object with them) otherwise they will be lost on the next loop iteration.
You can omit the check for if (userChoice == 3) since this would never happen in combination with the while (userChoice != 3).
Example input:
Enter:
1.Enter Nmame
2.Enter another name
3.Exit
1
Enter name
John Doe
1.Enter Nmame
2.Enter another name
3.Exit
3
this code actually inside if statements (to decide if it a lecturer or student, but the problem are same for both, the input name got skipped)
Lecturer a = new Lecturer();
System.out.print("Please enter your Lecturer Identification Number, Sir : ");
input.nextLine();
a.setLect_num(input.nextLine());
System.out.print("\nPlease insert your Name, Sir : ");
a.setName(input.nextLine());
System.out.print("\nPlease enter your Age, Sir : ");
a.setAge(input.nextInt());
System.out.print("\nPlese enter the course you are in charge, Sir : ");
input.nextLine();
a.setCourse(input.nextLine());
a.setOccupation("Teacher");
a.introduction();
In line 2 of your code snippet, you are collecting input from the scanner and discarding it:
System.out.print("Please enter your Lecturer Identification Number, Sir : ");
input.nextLine(); // this line is gathering input and discarding it
a.setLect_num(input.nextLine());
So I have my code compile but when I run it it combines my lines
System.out.print("Enter ID Number");
double ID=s.nextDouble();
if(ID >9999|| ID<0)
ID=0;
System.out.print("Enter Make of Vehicle");
String make=s.nextLine();
System.out.print("Enter Model of Vehicle");
String model=s.nextLine();
System.out.print("Enter Color of Vehicle");
String color=s.nextLine();
System.out.print("Enter Year");
double year=s.nextDouble();
if(year <2000 || year>2017)
year=0;
When I run the program it combines the lines to say
enter make of vehicle enter model of vehicle
How do I stop this as they are supposed to be separate entries
Use System.out.println instead of System.out.print
Put s.nextLine() after reading double. The problem is that s.nextDouble(); does not consume new line character, so s.nextLine(); after System.out.println("Enter Make of Vehicle"); is called automatically, you don't see anything more because there is only this one new line character (and it is being consumed).
double ID=s.nextDouble();
s.nextLine();
if(ID >9999|| ID<0)
ID=0;
Second thing is to replace System.out.print with System.out.println to print output in new line.
Call s.nextLine() after double ID=s.nextDouble(), couse nextDouble() doesn't consume the \n
I am now having a difficult time fixing this problem.
So, I have this code snippet here which asks 3 input from the user.
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.next();
System.out.print("Enter account PIN: ");
pin = input.next();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;
But everytime I run it, it always skips the input for the String "name", I tried using input.next(); on it and it works but then it will now skip the input for String "accnum".
EDIT: It also just happens if the input from "name" has a space on it, for example : John Doe.
Am I missing something here?
The nextLine() gobbles the newline character produced by the next() of account pin (when you hit enter). So, it won't ask for name. Add input.nextLine() after pin = input.next(); and try
Try This. i think problem with next(). since next reads input as tokens with default delimiter(i think space is the default delimiter).:
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.nextLine();
System.out.print("Enter account PIN: ");
pin = input.nextLine();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;
If you're using input anywhere before this block of code, then you need to be sure to call nextLine earlier on.
If you use next instead, then your input stream will still contain a new line character (\n). Thus, when you start this block of code with nextLine, that call will take the previous \n and not the name which was just entered.
In general, if your Scanner is reading System.in, then you should use nextLine everywhere. next, nextInt, and the other next methods are meant for more predictable data.
Okay, thats for the help everyone, I managed to fix it by adding "input.nextLine();" before "name = input.nextLine();"
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:
"Enter the second student's name: Enter the student's score: "
instead of
"Enter the second students's name: "
"Enter the student's score: "
I also can not input data into the System.out.print method of the second student
My main code where the error is:
System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
System.out.print("Enter the students's score: ");
score = reader.nextInt();
student1.setScore(i, score);
}
System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
System.out.print("Enter the students's score: "); //program skips to here to input
//data
score = reader.nextInt();
student2.setScore(i, score);
}
the part that deals with the error from the class is as follows
public void setName(String nm){
name = nm;
}
You should call println() to print a newline character, after reading the input.
If by "overlapping" you mean they appear on the same line then you want System.out.println, rather than System.out.print. println emits a trailing newline.
Could you more clearly describe this 'overlapping'? In your original question your 'one versus the other' were identical. Make it a code sample if need be to preserve spacing and such,
I believe you are talking about how all the lines are printed on the same line. You need to either use line break characters '\n' in Java, or use System.out.println
Try inserting:
reader.nextLine();
...before
System.out.print("Enter the second student's name: ");
.nextInt() doesn't swallow the newline from your input, so the next call to nextLine() just gets the newline character and returns you an empty string - and the program continues, printing the next line of output.
If what I understand is right, you may probaly have problems with the input of the java console. I can't tell much because there's not enough information, but maybe you can refer this link for getting input in java console: http://www.abbeyworkshop.com/howto/java/readLine/index.html
And I recommend clearing the un-affected code (about class Student), just check the input & output from console only.