How to output a long string from Scanner input in Java [duplicate] - java

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(16 answers)
Closed 2 years ago.
class Property {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String[] rooms = new String[15];
System.out.println("How many rooms? ");
int roomLimit = input.nextInt();
for (int i = 0; i < roomLimit; i++) {
System.out.println("Enter room name " + (i + 1));
rooms[i] = input.next();
}
When I enter room names that are single words like, 'double, single, master, etc.', the list of room names displays fine. But when I enter room names with more than one word, only the first word is listed, and the second word of the first room name automatically becomes the second room name as shown below.
How many rooms?
4
Enter room 1
Double Duluxe
Enter room 2
Enter room 3
Couple Golden
Enter room 4
List of Chosen Rooms
Room 1: Double
Room 2: Duluxe
Room 3: Couple
Room 4: Golden
Process finished with exit code 0

Just use the method Scanner.nextLine() instead of using Scanner.next().
Scanner.next() , according to the docs:
Finds and returns the next complete token from this scanner.
This means that it will only read the first word (the token, in your case). Scanner.nextLine(), on the other hand (docs):
(...) returns the rest of the current line, excluding any line
separator at the end.
Which means it will read the entire line.
Your code will look like this after the change:
// ...
System.out.println("Enter room name " + (i + 1));
rooms[i] = input.nextLine();
// ...

Related

Java: Why while(true) loop breaks automatically when using nextInt()? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am a beginner programmer student from Finland, this is my first post here so hello everyone! So, I am writing this Java program that reads user inputs and creates new Books according to the inputs and then adds them to list and sorts them according to their recommended ages and names. The following code doesn's seem to work, the loop breaks automatically after one go. I actually fixed the issue using "Integer.valueOf" instead of nextInt but I started wondering why the nextInt doesn't work here?
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Book> books = new ArrayList<>();
while (true) {
System.out.println("Enter books name, blank will end the loop:");
String bookName = reader.nextLine();
if (bookName.equals("")) {
break;
}
System.out.println("Enter the books recommended age:");
int minimAge = reader.nextInt();
Book book = new Book(bookName, minimAge);
books.add(book);
}
System.out.println("Total " + books.size() + " books.");
System.out.println();
System.out.println("Books:");
Comparator<Book> vertaus = Comparator
.comparing(Book::getMinimAge)
.thenComparing(Book::getName);
Collections.sort(books, vertaus);
for (Book k : books) {
System.out.println(k);
}
}
}
While entering number for minimAge when you press enter, the scanner takes two input, the number and a EOF character. As a result EOF character is set as the next bookname. Which is equivalent to empty string and breaks the loop. To skip this add the following code
int minimAge = reader.nextInt();
reader.nextLine();

Using a for loop to add names to an array in java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I am writing a code that asks for user input on the names of the players and stores them in array. To do this I am using a for loop, which i thought would be more efficient, however, the code seems to do something unexpected, and I cannot see why it is doing what it does. Below is the code and the result:
Scanner reader = new Scanner (System.in);
System.out.print("Please enter the number of players:");
int players = reader.nextInt();
String[] player_name = new String[players+1];//Array to store player names
for (int i = 0; i < players; i++)//Loop to ask players their name
{
System.out.print("Player " + (i+1) + " please enter your name:\n");//Asks player names one by one
player_name[i] = reader.nextLine();//Saves the player names to the array
}
And here is the result when the number of players is 2:
Please enter the number of players:2
Player 1 please enter your name:
Player 2 please enter your name:
wa
BUILD SUCCESSFUL (total time: 23 seconds)
When I hit enter after typing the "name" wa to type player 2's name the program just ends.
The nextInt() doesn't grab the end of line character, AKA the "enter" after the number is entered. Instead you can use nextLine() and get the entire line and then parse it into an Integer like so
int players = Integer.parseInt(reader.nextLine());

"for" loop does not iterate the way I want [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am trying to get the name and jersey number of 3 hockey players from the user. I then make an object from my created class called HockeyPlayer with the data I have. I then put it into the array. The second iteration does not work. Please help! Thank you in advance.
ArrayList<HockeyPlayer> array = new ArrayList<HockeyPlayer>();
//For loop to input names
for(int i=0; i < 3; i++)
{
System.out.print("Enter name of Player " + i +":");
startName = keyboard.nextLine();
System.out.print("Enter jersey number of Player " + i +":");
playNum = keyboard.nextInt();
//Make objects and add to array
HockeyPlayer p = new HockeyPlayer(startName, playNum);
array.add(p);
}
keyboard.close();
The problem here is that in every iteration of your loop, you make a call to nextLine(), then a call to nextInt(), but after you make the call to nextInt(), the newline character has not been read. Basically, if the input is something like
First Player Name
1
Second Player Name
2
then, after the first iteration of your loop, the Scanner has just finished reading in the 1, but not the newline right after it. Hence, in the second iteration, the nextLine() deals with the newline after 1, but only that newline. Then, the nextInt() call will try to turn Second into an int, and throws the InputMismatchException.
Common ways of going around it are to either put another nextLine() call right after the call to nextInt() (and just throw away this extra newline), or to just read in the line with the number all at once with a call to nextLine(), and parse out the int using Integer.parseInt().
From InputMismatchException's JavaDoc:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
It seems that you entered a string whereas nextInt() expects an integer.
If by second iteration you mean the second for, you probably have to override your HockeyPlayer.toString() method.
public String toString() {
return name+" "+startNum;
}
I assume your keyboard variable is of type java.util.Scanner. If that is true then you need to call keybord.reset() at the end of loop.
Your problem is that keyboard.nextInt() does not consumes end of line which is produced when you hit enter. This end of line character is responsible for your exceptions.
This code works:
HockeyPlayer [] hArr = new HockeyPlayer[3];
for(int i=0; i < 3; i++)
{
String startName = "";
Scanner scanner = new Scanner(System.in);
int playNum = 0;
System.out.print("Enter name of Player " + i +":");
startName = scanner.nextLine();
System.out.print("Enter jersey number of Player " + i +":");
playNum = scanner.nextInt();
scanner.reset();
HockeyPlayer p = new HockeyPlayer(startName, playNum);
hArr[i] = p;
}
It is good to go with:
int playNum = Integer.parseInt(sc.nextLine());

Java Loop/User Input from Scanner

Making just a simple basketball program where I ask for the home team name, how many games are in the season, and then in a loop ask for the next team game. Basically when I start the do-while loop, it works great, unless the user types in for example, "Ohio State." The out put will then go from "6 games remaining" to "4 games remaining" for example. Usually it will just ask opponent?, then decrement by one game.
How can I fix so that a 2 word basketball team name doesn't decrement twice?
import java.util.Scanner;
public class Basketball2 {
public static void main(String[] args) throws java.io.IOException {
Scanner scanInput = new Scanner(System.in);
String sHomeTeam;
String sAwayTeam;
int iNumGames;
int iGamesLeft = 0;
System.out.println("Enter home team's name: ");
sHomeTeam = scanInput.nextLine();
System.out.println(sHomeTeam);
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
System.out.println(iNumGames);
//start looping
do {
System.out.println("Enter opponent team's name: ");
sAwayTeam = scanInput.next();
System.out.println(sAwayTeam);
iGamesLeft = --iNumGames;
System.out.println("There are " + iGamesLeft + " games left in the basketball season");
}//end do
while(iGamesLeft > 0);
Replace: sAwayTeam = scanInput.next(); with sAwayTeam = scanInput.nextLine(); The reason it loops twice is because scanInput.next(); only returns one token (e.g. word) at a time. When you enter two words it doesn't need receive more input from the user before continuing a second time because it already has another word to return. Hence the double loop.
You also need to take care of the line of code that calls nextInt(). This works like the next() method, but, instead of a token (word), it scans in just one character as an int. Try this: after iNumGames = scanInput.nextInt(); put scanInput.nextLine(); This should clear scanInput of anything that is making it skip. Note: because of the way that your code is written, this will only read one character. If you need to read more than one character you should use nextLine() and assign its value to an integer.
Whatever is said in the answer given by Donny Schrimsher is correct. All that you have to do now is after getting the number of games in the home team's basketball season i.e.
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
You have to add
scanInput.nextLine();
This is because after entering the number of games you press enter key (end of line) and nextInt() method takes the number of games and not the end-of-line. This end-of-line is consumed by the nextLine() method which Donny Schrimsher mentioned in the do-while loop. SO to avoid this you add an extra nextLine() method.
Thus it has to be
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
scanInput.nextLine();
System.out.println(iNumGames);
plus the changes mentioned by Donny Schrimsher.
Thanks
try below code with all exit functionality also.
import java.util.Scanner;
public class Basketball2 {
public static void main(String[] args) throws java.io.IOException {
Scanner scanInput = new Scanner(System.in);
String sHomeTeam;
String sAwayTeam;
int iNumGames;
int iGamesLeft = 0;
System.out.println("Enter home team's name: ");
sHomeTeam = scanInput.nextLine();
System.out.println(sHomeTeam);
System.out
.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
System.out.println(iNumGames);
// start looping
do {
System.out.println("Enter opponent team's name: ");
scanInput = new Scanner(System.in);
sAwayTeam = scanInput.nextLine();
if(!"".equals(sAwayTeam.trim()) && !"exit".equals(sAwayTeam.trim()))
{
System.out.println(sAwayTeam);
iGamesLeft = --iNumGames;
System.out.println("There are " + iGamesLeft+ " games left in the basketball season");
}
}// end do
while (iGamesLeft > 0 && !"exit".equalsIgnoreCase(sAwayTeam));
}
}
Subject: 'Java Loops' with Scanner
The simple Java program I wrote is working perfectly, you can try for yourself...and you also can convert this program easily into 'while loop', 'do - while loop' and 'for - each loop'.
Rafiq,
VA, USA,
Dated: 04/17/2015
//Examples: 'for loop' with Scanner
package com.java_basics;
import java.util.Scanner;
public class ForLoop_Examples_With_Scanner
{
public static void main(String[] args)
{
//Creating instance of Scanner to allows a user's input to read from System.in
Scanner mySC = new Scanner(System.in);
System.out.println("Please, enter the value of 'int i' between '0 and 2' : ");
int i = mySC.nextInt();
System.out.println("Please, enter the value of 'exitPoint' between '10 and 1000' :");
int exitPoint = mySC.nextInt();
System.out.println("Please, enter the value of 'increment' between '1 and 2' :");
int increment = mySC.nextInt();
mySC.close();//Releasing memory to the OS (Operating System) for reuse
System.out.println("Output:\n" + "======");
for(;i<exitPoint ; i=i+increment)//i++==>i=i+1==>i=i+increment
{
System.out.println(i);
}
}
}

Why is first for loop iteration skipped?

my code is yielding an unexpected result. It seems my for loop skips the first iteration and I don't understand why.
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
int number;
// Ex.1.
String family_name;
String[] family_array;
System.out.println("Enter number of family members: ");
number = get.nextInt();
family_array = new String[number];
for(int i = 0; i < number; i++){
System.out.println("Enter family member name: ");
family_name = get.nextLine();
family_array[i] = family_name;
}
for(int i = 0; i < number; i++){
System.out.println(family_array[i]);
}
}
Returns... (pretend the number input are names)
Enter number of family members:
5
Enter family member name:
Enter family member name:
1
Enter family member name:
2
Enter family member name:
3
Enter family member name:
4
1
2
3
4
Why is the first get.nextLine() skipped?
Currently your call to Scanner#nextInt is not consuming the newline character so it is being passed through to your first call of Scanner#nextLine, therefore it does not block.
You will need to add
get.nextLine();
after calling nextInt so that your first call to nextLine will block for IO.
Notice that blank line between 4 and 1?
4
//this is it
1
When you call get.NextInt() you'd not eating the whole line, just the next int. The empty rest of the line is eaten in your first loop iteration. Add a call to get.nextLine() after reading the int.
What worked for me was instantiating a new Scanner in each iteration:
for(int i = 0; i < number; i++)
{
System.out.println("Enter family member name: ");
Scanner loopGet = new Scanner(System.in);
family_name = loopGet.nextLine();
family_array[i] = family_name;
}
I am going to say it is because you still have a buffered CR/LF - so the first one is set to blank. Notice the blank line as you print your family names (numbers). That is your blank family name.
The keyboard input is a buffered stream - it has your 5, and it has a CR/LF (or perhaps just a LF, depending on your OS).
You probably want to get the LINE and then do a string.convert, atoi, system.convert (whichever one is for Java) to get the #.
number = get.nextInt();
// if i enter 4 then it will 4\n and nextInt will take only 4
// and the \n will be taken as input by the getline.
get.nextLine();
//this will return the "" from ""\n . so adding this will solve your problem
family_array = new String[number];

Categories

Resources