This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I have following class
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = sc.nextInt();
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
I can't type song name nr 1 because it Always shows first two together.
Like this if I type 3:
How many songs do your CD contain?
3
Please enter song nr 1:
Please enter song nr 2:
Change
int songs = sc.nextInt();
to:
int songs = Integer.parseInt(sc.nextLine().trim());
and it will work fine.
You should not mix usages of nextInt with nextLine.
add sc.nextLine(); after int songs = sc.nextInt();
Once you enter a number and read it using a scanner ( as a number) using sc.nextInt();, the newline character will be present in the input stream which will be read when you do sc.nextLine(). So,to skip(over) it, you need call sc.nextLine() after sc.nextInt();
Add a sc.nextLine() after sc.nextInt() and your code works fine.
The reason is the end of line after you type the nomber of songs.
Either use nextInt or nextLine, I would opt for nextLine:
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt()
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
put a sc.nextLine(); after int songs = sc.nextInt();
Related
So I have a program that takes orders for vehicle purchases (meant to learn the basics of java. Right now this iteration of the assignment is focusing on inheritance). Hierarchy: Orders.java (Main program), Vehicle.java (parent class), Boat.java/Car.java/Truck.java(child classes).
I was showing my menus manually in the main program before but tried to delegate that responsibility to my Vehicle class so it would be more generic and each child could pass in a Question Prompt and Array of Choices to the showMenu function. So nothing was being done manually anymore.
Here's what happened when it was done manually (worked fine):
System.out.println("What type of Car is this?");
System.out.println("\t1. Sedan");
System.out.println("\t2. Coupe");
System.out.println("\t3. Wagon");
System.out.print("Choice: ");
while (!sc.hasNext("[123]")) {
System.out.println("");
System.out.println("");
System.out.println("That's not an option! Please try again.");
System.out.println("What type of Car is this?");
System.out.println("\t1. Sedan");
System.out.println("\t2. Coupe");
System.out.println("\t3. Wagon");
System.out.print("Choice: ");
sc.next();
}
choice = sc.next();
if(choice.equals("1")){
car.setCarType("Sedan");
} else if (choice.equals("2")){
car.setCarType("Coupe");
} else if (choice.equals("3")){
car.setCarType("Wagon");
} else{
car.setCarType("unknown");
}
Here's how it works now (crashes before stopping to let the user give input):
public int showMenu(String prompt, String[] choices){
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
String choiceIdentifiers = "";
int choice;
for(int i = 0; i < choices.length; i++){
Integer j = i+1;
System.out.println("\t\t" + j + ". " + choices[i]);
choiceIdentifiers = choiceIdentifiers + j.toString();
}
System.out.print("Choice: ");
while (!sc.hasNext("[" + choiceIdentifiers +"]")) {
System.out.println("");
System.out.println("");
System.out.println("That's not an option! Please try again.");
System.out.println(prompt);
for(int i = 0; i < choices.length; i++){
System.out.println("\t\t" + (i+1) + ". " + choices[i]);
}
System.out.print("Choice: ");
sc.next();
}
choice = Integer.parseInt(sc.next());
sc.close();
return choice - 1;
}
Also here's a link to my github repo with the full program.
What could be happening in the showMenu function to crash the program and throw the NoSuchElementException?
Any help would be greatly appreciated.
The problem is that you're closing the System.in stream when you call sc.close().
When you construct a new Scanner that uses the closed System.in stream and you call next() on it, you'll get this error.
To solve the problem, don't close the System.in (don't call close() on any Scanner that uses this stream) until you're done processing user input.
Here is a MCVE:
public class Example {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
sc1.close();
Scanner sc2 = new Scanner(System.in);
sc2.next();
}
}
The problem is in Vechile.java show menu method
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
String choiceIdentifiers = "";
int choice;
for(int i = 0; i < choices.length; i++){
Integer j = i+1;
System.out.println("\t\t" + j + ". " + choices[i]);
choiceIdentifiers = choiceIdentifiers + j.toString();
}
so here after iterating on choices array you are concatinating choiceIdentifiers string that will become 12 after loop but you are expecting input from user as 1 or 2 for model type of vechile so if you will put 1 for model then
!sc.hasNext("[" + choiceIdentifiers +"]")
is not having 1 so it will throw no such element error , hope this will help you
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();
...
I am trying to use a menu system that can delete a customer from my array myHotel[], this is built from an object.
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
...
public void deleteCustomer(String myHotel[]){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
roomNum=input.nextInt();
myHotel[roomNum].setName("e");
}
I get the errors, cannot find symbol?
Here is the Full Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int roomNum=0;
Room[] myHotel = new Room[10];
for (int x =0; x<10; x++){
myHotel[x] = new Room();
}
String roomName;
String menu;
do {
System.out.println("Please Select an Option from the Menu:");
System.out.println("Enter V to View all Rooms");
System.out.println("Enter A to Add Customer to Room");
System.out.println("Enter D to Delete Customer from Room");
System.out.println("Enter Q to Quit");
menu=input.next();
//if(menu.charAt(0) == 'V')viewAllRooms();
//if(menu.charAt(0) == 'A')addCustomer();
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
} while (menu.charAt(0) != 'Q');
while (roomNum < 10) {
for (int x = 0; x < 10; x++ )
if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
for (int x = 0; x < 10; x++) {
//System.out.println("room " + x + " occupied by " + myHotel[x].mainName);
System.out.println("room " + x + " occupied by " + myHotel[x].getName());
}
}
}
public void deleteCustomer(String myHotelRef){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
int deleteRoom=input.nextInt();
myHotelRef[deleteRoom].setName("e");
}
}
You get multiple errors. What is myHotel[]? roomNum is not defined, etc.
Please use your compiler.
Also: please read https://stackoverflow.com/help/how-to-ask :-)
First you need declare myHotel array and pass it with out [].
deleteCustomer(myHotel);
Second, there is not such a method setName(String name) in String class
myHotel[roomNum].setName("e");// no such a method
Third, you need to declare the roomNum variable like:
int roomNum = input.nextInt();
Your main problem is that you've included [] in your call to deleteCustomer. It should be:
if (menu.charAt(0) == 'D') {
deleteCustomer(myHotel);
}
When you reference an array object as a whole you don't include square brackets. Square brackets are for the declaration, initialisation and for accessing individual elements within the array.
I'd also recommend that you get into the habit of always using curly braces with your if, for and while constructs, as not including them is often the cause of bugs. It also makes it easier to read when you come back to it, and you're clearly indicating to others what should be part of the loop and what shouldn't.
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();
}
}
My program requires users to input some data. My problem is, when it runs, it shows the first question and then immediately moves to the second question, without waiting for the user input. My friend suggested putting sc.nextLine(), it did work for the first time, but when it looped back it gave me an additional space and actually saved the space to my obj.
To illustrate, when i run it, it shows:
Original: Enter position no 1: How many seats?(use can input)
With the additional sc.nextLine: Enter position no 1: (user can input)
How many seats:
BUT second time it shows: Enter position no 2: (user can input)
(and then space)
and then the succeeding question: How many seats:
Below is my whole code in my main class. Thanks in advance.
package election;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.StringBuilder;
public class Election {
public static void main(String[] args) {
int maxpos;
int count;
int maxcan;
int cancount;
String name;
int num;
String position;
int posnum;
int seat;
String party;
int vote;
Scanner sc = new Scanner(System.in);
ArrayList<Candidate> list = new ArrayList<Candidate>();
Candidate c;
do{
System.out.print("How many positions for this election: ");
maxpos = sc.nextInt();
for(count = 1; count<=maxpos; count++){
System.out.print("Enter position no. " + count + ": ");
position = sc.nextLine();
sc.nextLine();
posnum = count;
System.out.print("How many seats: ");
seat = sc.nextInt();
System.out.print("Enter number of candidates: ");
maxcan = sc.nextInt();
for(cancount = 1; cancount<=maxcan; cancount++){
System.out.print("Enter candidate no. " + cancount + " name: " );
name = sc.nextLine();
num = cancount;
System.out.print("Enter candidate no. " + cancount + " party: " );
party = sc.nextLine();
c = new Candidate(name, num, position, posnum, seat, party);
list.add(c);
}
}
}while(!(count > maxpos));
for(int i = 0; i<list.size(); i++){
list.get(i).displayInfo();
}
}
}
Whenever you use nextInt(), you need to put nextLine() after it
System.out.print("How many seats: ");
seat = sc.nextInt();
sc.nextLine();
System.out.print("Enter number of candidates: ");
maxcan = sc.nextInt();
sc.nextLine();
This will consume the unconsumed \n character from stream
Instead of using the Scanner, you can use readLine() of DataInputStream
DataInputStream din=new DataInputStream(System.in);
System.out.print("Enter number of candidates: ");
int maxcan =Integer.parseInt(din.readLine());