-1

I want to print a string formed by concatenating two strings: the first one is declares; the second one is inputed via nextLine(). While this code works when I enter two strings with one space as input, it doesn't work when I try to enter a sentence.

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 iq;
        double dq;
        String sq;

        iq=scan.nextInt();
        dq=scan.nextDouble();
        sq= scan.nextLine();


        /* Read and save an integer, double, and String to your variables.*/
        // Note: If you have trouble reading the entire String, please go back and review the Tutorial closely.

        /* Print the sum of both integer variables on a new line. */
        System.out.println(i+iq);
        System.out.println(d+ dq);
        s= s.concat(sq);
        System.out.println(s);

        /* Print the sum of the double variables on a new line. */

        /* Concatenate and print the String variables on a new line; 
            the 's' variable above should be printed first. */

        scan.close();
    }
}
Sterconium
  • 541
  • 4
  • 19

1 Answers1

-1

First of All, Above mentioned code is not working with any String or Sentence. It is known issue that Scanner will not work expectedlywhen you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method .

WorkAround:

add Scan.nextLine() after scan.nextDouble()

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 iq;
        double dq;
        String sq;

        iq=scan.nextInt();
        dq=scan.nextDouble();
        scan.nextLine();
        sq= scan.nextLine();



        /* Read and save an integer, double, and String to your variables.*/
        // Note: If you have trouble reading the entire String, please go back and review the Tutorial closely.

        /* Print the sum of both integer variables on a new line. */
        System.out.println(i+iq);
        System.out.println(d+ dq);
        s= s.concat(sq);
        System.out.println(s);

        /* Print the sum of the double variables on a new line. */

        /* Concatenate and print the String variables on a new line; 
            the 's' variable above should be printed first. */

        scan.close();
    }
}