-3

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 ?

1 Answers1

0

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);
Elarbi Mohamed Aymen
  • 1,480
  • 1
  • 11
  • 25