Reputation: 53
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/* Read input */
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine(); // gets rid of the pesky newline
String s = scan.nextLine();
scan.close();
/* Print output */
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
The above code works perfectly fine in hackerrank compiler. While if i run it on IntelliJ, one extra call to scan.nextLine() is required in order to read the actual string.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/* Read input */
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine(); // gets rid of the pesky newline
scan.nextLine(); // gets rid of the pesky newline
String s = scan.nextLine();
scan.close();
/* Print output */
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
Can someone help me with why this could happen? I am assuming the call to nextDouble() would ignore the \n left in the buffer by nextInt() and pickup the next double token and leave a new \n in the buffer. So a single call to nextLine() should be enough to clear that \n from buffer, but why 2 calls are needed when I run this on IntelliJ.
Is this a JAVA version issue or is there something really basic which I am missing?
Upvotes: 0
Views: 68
Reputation: 5075
You probably see the effect of this official IDEA issue: Console readLine skips input in 2022.1.1
You could update to 2022.1.2 where this is fixed.
Upvotes: 1