This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am not able to use nextLine method after using nextInt method.This is the note given below....
note in hacker rank:(If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
The nextLine method is not getting skiped but it is empty.
Code:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d=scan.nextDouble();
String s=scan.nextLine();
// Write your code here.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
Output:
String:
Double: 3.1415
Int: 42
In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
That's because the Scanner class' nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner class' nextLine().
You can fire a blank Scanner class' nextLine() call after Scanner#nextInt to consume the rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
You may try this.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
double y = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + y);
System.out.println("Int: " + x);
}
Yes it reads the remaining line which is empty. So while giving input pass whitespaces you will see the output, instead of printing string print it's length
When you are entering the integer for nextInt() then immediate you pres enter key and this enter key caught by nextLine(). s stores enter and that is known as whitespace so it not shows.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 27 days ago.
I am trying to read a String and output it to the terminal, as well as a few primitives, but it does not seem to work. The code is below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s = scan.nextLine();
scan.close();
System.out.println("String: " + s + "\n");
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
I have tried to find other ways to parse the string in the Scanner class, but none of them seemed to work. What I except is for the String to be properly read and outputed to the terminal, along with the few other values.
Thanks in advance.
The problem is that when you press enter (when you digit the number) you are inserting a \n character inside the buffer, so when you will call nextLine() you will read the \n (because nextLine reads the input until the \n) and you will not be able to write anything because the function returns when found the \n.
You can clean it calling scanner.nextLine() one more time
int i = scan.nextInt();
double d = scan.nextDouble();
// Remove \n from buffer
scan.nextLine();
String s = scan.nextLine();
I am doing a very basic Java program :
import java.util.Scanner;
public class App {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int nbrFloors = 0;
int nbrColumns = 0;
int nbrRows = 0;
System.out.println("So you have a parking with " + Integer.toString(nbrFloors) + " floors " + Integer.toString(nbrColumns) + " columns and " + Integer.toString(nbrRows) + " rows");
System.out.print("What's the name of your parking ? ");
String parkName = sc.next(); //or sc.nextLine() ?
System.out.print("How much should an hour of parking ? If you want your parking to be free please type in '0' : ");
float intPrice = Float.parseFloat(sc.next());
Parking parking = new Parking(nbrFloors, nbrColumns, nbrRows, parkName, intPrice);
}
}
As you can see on line 16 I use the Scanner.next() method because using Scanner.nextLine() skips user input. However I learned in this thread Java Scanner why is nextLine() in my code being skipped? that when you use the Scanner.next() method it skips whatever is after the first word you entered.
So I wonder how you can ask for a user input, while both not skipping it (because Scanner.nextLine() does that) and reading the whole input ?
Your code skips user input because nextLine() method reads a line up-to the newLine character (carriage return). So after nextLine() finishes the reading the carriage return actually stays in the input buffer. That's why when you call sc.next(), it immediately reads the carriage return from the input buffer and terminates the reading operation. What you need to do is implicitly clear the input buffer after a read-line operation. To do that, simply call sc.next() one time after line 16.
System.out.print("What's the name of your parking ? ");
String parkName = sc.nextLine();
sc.next();
System.out.print("How much should an hour of parking ? If you want your parking to be free please type in '0' : ");
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
Im writing code to read an integer value, maybe a float, a double, and then finally read a string. What happens is that I enter the int, press enter after which the execution should stop until I enter a string. However, as soon as I press the enter to go to a newline, I get the outout which is only the number, because execution doesnt pause for me to enter the string. Whats going on
Tried inputting number and then string, that works. Tried inputting number followed by number,that works, tried inputting several strings, that works, but i couldnt get the program to read a number and then a string.
package test;
import java.util.Scanner;
public class Trying {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d=scan.nextDouble();
String s=scan.nextLine();
scan.close();
System.out.println("String: \'" + s+"\'");
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
I dont get an output for the string
Your problem is with using Scanner.nextLine() and Scanner.nextDouble() / Scanner.nextInt() together. You should be careful when using these together, as they might result in unexpected behavior. You can read the JavaDocs of the Scanner class for more detailed information. Instead of int i = scanner.nextInt(); double d = scanner.nextDouble(), try using double d = Double.parseDouble(scanner.nextLine()) to read in a String and convert it to a double.
You need to clear buffer in scanner before accepting a string input so just write
scan.nextLine();
before
String s=scan.nextLine();
and it shall work
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was solving a problem on Hackerrank in which I have to input an integer , a double and a string and print the result using stdout.
Input
42
3.1415
Welcome to HackerRank's Java tutorials!
Output
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42
I wrote the following code and i'm not able to pass my test cases:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String ss = s.nextLine();
int i = s.nextInt();
double d = s.nextDouble();
System.out.println("String: "+ss);
System.out.println("Double: "+d);
System.out.println("Int: "+i);
}
}
is there anything wrong in the code?
The question also states that :-
Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
Following was my output:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Solution.main(Solution.java:8)
Can anyone please explain this ?
the trick is to add s.nextLine(); before getting the String because it will reads the remainder of the line with the number on it (with nothing after the number I suspect)
Try placing a s.nextLine(); after each nextInt() if you intend to ignore the rest of the line.
so the full code will be like :
Scanner s = new Scanner(System.in);
int i = s.nextInt();
double d = s.nextDouble();
s.nextLine();
String ss = s.nextLine(
System.out.println("String: "+ss);
System.out.println("Double: "+d);
System.out.println("Int: "+i);
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.