Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

How to scan String?

Question: Sample Input ---> 42, 3.1415,Welcome to Hackerrank Java tutorials!

Sample Output ----> String: Welcome to Hackerrank Java tutorials! Double: 3.1415 Int: 42

My codes are here:

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);
}

}

I really don't understand what is wrong with this. That is really easy question but I am missing something. Could anyone help me about it?

2 Answers

I have a hackerrank account and this is my work for this problem:

import java.util.Scanner;

public class Solution {

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

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

}

The reason why you have to include sc.nextLine() after you read in an integer and double is to get rid of '\n'.

is there any specific reason to do it like that? Paolo Villanueva

It's been so long since I've done Java myself but I will try to explain it.

nextInt() and nextDouble() only scans and gets the next int and double in the input buffer. It doesn't read in anything else. In this case, it doesn't read the new line character. If you want to read in the next line, you have to use nextLine()