0

I'm trying to learn Java through Hackerrank and the challenge that I'm working on currently takes an int, double, and string and prints them on separate lines in reverse order, but I haven't been able to get the string to print.

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            int x=sc.nextInt();
            double y=sc.nextDouble();
            String s=sc.nextLine();

            System.out.println("String: "+s);
            System.out.println("Double: "+y);
            System.out.println("Int: "+x);
         }
    }

The input is:

42
3.1415
Welcome to Hackerrank Java tutorials!

And output is:

String:
Double: 3.1415
Int: 42

I don't know Java at all, but from the code I've seen online, I can't tell why this is wrong.

ashiquzzaman33
  • 5,451
  • 5
  • 29
  • 39
  • Related answer: http://stackoverflow.com/questions/19077908/beginner-trying-to-program-a-simple-calculator/19077970#19077970 – Nayuki Sep 20 '15 at 22:30
  • Related answer: http://stackoverflow.com/questions/18163518/while-loop-executes-only-once/18163608#18163608 – Nayuki Sep 20 '15 at 22:31

2 Answers2

2

Change the first part of the code to this:

        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        double y = sc.nextDouble();
        sc.nextLine();  // Discard rest of current line
        String s = sc.nextLine();

The way java.util.Scanner splits the input into numbers or lines is a bit weird.

Nayuki
  • 16,655
  • 5
  • 47
  • 75
-1

The sc.nextLine(); should instead be sc.next();

Beryllium
  • 546
  • 7
  • 19