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();
Related
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();
// ...
This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 5 years ago.
how to take more inputs from user using Nextline() in java
if i use scn.Nextline() after reading one input it will work but giving a null in answer.
public class Mapdemo {
public static void main(String[] args) {
Scanner scn =new Scanner(System.in);
System.out.println("enter the number of phoneaddress you want to store");
int n=scn.nextInt();
int j=0;
System.out.println("enter the phonenumber first and then name of the person phoneaddress");
Map<String, Long> m1=new HashMap<String,Long>();
for(int i=0;i<n;i++)
{
Long l=scn.nextLong();
String s=scn.nextLine();
m1.put(s,l);
}
System.out.println("enter the name to be checked");
String s2=scn.next();
System.out.println(m1.get(s2));
After using .nextInt() for the first time do:
scanner.nextLine();
after that to clear the line, nextLine() stops at the newline character (OS dependant).
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I'm trying to write a code that asks a user to input their name, stores it in a List, then asks them to input their age, stores it in another list. It then asks the user if they would like to try again [Y/N].
When testing the code, I inputted "Y" and expected the loop to ask me to input another name. Instead, it skips through the name input and jumps to the age input. I can't figure out why.
Here's the code
import java.util.ArrayList;
import java.util.Scanner;
public class PatternDemoPlus {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
String repeat = "Y";
while(repeat.equalsIgnoreCase("Y")){
System.out.print("Enter the name: ");
names.add(scan.nextLine());
System.out.print("Enter the age: ");
ages.add(scan.nextInt());
System.out.print("Would you like to try again? [Y/N]");
repeat = scan.next();
//Notice here that if I use "repeat = scan.nextLine(); instead, the code does not allow me to input anything and it would get stuck at "Would you like to try again? [Y/N]
System.out.println(repeat);
//Why is it that after the first iteration, it skips names.add and jumps right to ages.add?
}
}
}
I would appreciate your help. Thank you.
Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.
Try to change your code like below.
public class PatternDemoPlus {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
String repeat = "Y";
while(repeat.equalsIgnoreCase("Y")){
System.out.print("Enter the name: ");
String s =scan.nextLine();
names.add(s);
System.out.print("Enter the age: ");
ages.add(scan.nextInt());
scan.nextLine();
System.out.print("Would you like to try again? [Y/N]");
repeat = scan.nextLine();
System.out.println(repeat);
}
}
}
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Just one question: why I must type answer = in.nextLine(); twice? If this line is single the program doesn't work as expected. Without second line the program doesn't ask you to enter a string.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String answer = "Yes";
while (answer.equals("Yes")) {
System.out.println("Enter name and rating:");
String name = in.nextLine();
int rating = 0;
if (in.hasNextInt()) {
rating = in.nextInt();
} else {
System.out.println("Error. Exit.");
return;
}
System.out.println("Name: " + name);
System.out.println("Rating: " + rating);
ECTS ects = new ECTS();
rating = ects.checkRating(rating);
System.out.println("Enter \"Yes\" to continue: ");
answer = in.nextLine();
answer = in.nextLine();
}
System.out.println("Bye!");
in.close();
}
}
The Scanner-Object has an internal cache.
You start the scann for nextInt().
You press the key 1
You press the key 2
You press return
Now, the internal Cache has 3 characters and the scanner sees the third character(return) is not a number, so the nextInt() will only return the integer from the 1st and 2nd character (1,2=12).
nextInt() returns 12.
Unfortunately the return is still part of the Scanner's cache.
You call nextLine(), but the Method scans its cache for a newline-marker that has been kept in the cache from before the nextInt() call returned.
The nextLine() returns a 0-length-string.
The next nextLine() has an empty cache! It will wait until the cache has been filled with the next newline-marker.
reset()
There is a more elegant way to clear the cache instead of using nextLine():
in.reset();
Because you are using nextInt() this method only grabs the next int it doesn't consume the \n character so the next time you do nextLine() it finishes consuming that line then moves to the next line.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :" );
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
String name= input.nextLine();
System.out.println("Your Next is : " + name);
}
}
nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.
If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.
Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.
If you call input.nextInt(); the scanner reads the number from the input, but leaves the line separator there. That means, if you call input.nextLine(); next, it reads everything till the next line separator. And this is in this case only the line separator itself.
You can fix that in two ways.
Way 1:
int ip = Integer.parseInt(input.nextLine());
// output
String name= input.nextLine();
Ways 2:
int ip = input.nextInt();
// output
input.nextLine();
String name= input.nextLine();
This one working, Anyway if you want to save IP address it must be String.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :");
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
input.nextLine();
String name = input.nextLine();
System.out.println("Your Next is : " + name);
}
}