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 ?