1

I'm working through a tutorial on Java and am having trouble on a trivial task. I need to be able to read a string from stdin and then concatenate it with another string and print it to stdout. Here is the code I'm using:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        Scanner scan = new Scanner(System.in);
        /* Declare second integer, double, and String variables. */
        int i2;
        double d2;
        String s2;
        /* Read and save an integer, double, and String to your variables.*/
        i2 = scan.nextInt();
        d2 = scan.nextDouble();
        s2 = scan.nextLine();
        /* Print the sum of both integer variables on a new line. */
        System.out.println(i2 + i);
        /* Print the sum of the double variables on a new line. */
        System.out.println(d2 + d);
        /* Concatenate and print the String variables on a new line; 
            the 's' variable above should be printed first. */
        System.out.println(s + s2);
        scan.close();
    }
}

According to How can I read input from the console using the Scanner class in Java?, I'm doing everything right, but the tutorial is showing s2 is being assigned an empty string and Java is only printing "HackerRank ".

What am I missing in my understanding of scan.nextLine()?

Community
  • 1
  • 1
brittenb
  • 5,849
  • 3
  • 30
  • 58

0 Answers0