Search code examples
javastring-concatenation

I want to know the reason Why I cannot concatenate my text With the variable in the code. How can I resolve this code?


I am trying to solve a problem in string concatenation But i don't understand it that why it only give me output like this While I am Using a "+" operator. Can anyone help me to clarify what is my problem . My code is

public static void main(String[] args) {
       int a;
       double b;
       String c;

       Scanner sc=new Scanner(System.in);
       a=sc.nextInt();
       b=sc.nextDouble();
       c=sc.nextLine();
       System.out.println(a+4);
       System.out.println(b+4.0);
       System.out.println("Hackerrank"+" "+c);


    } 

My input is:

12

4.0

is the best place to learn and practice coding!

My output is :

16

8.0

Hackerrank

But Expected Output is:

16

8.0

HackerRank is the best place to learn and practice coding!


Solution

  • The problem is not with the concatenation. It's the line c=sc.nextLine();. When you use c=sc.nextLine(); JVM assigns the value in the b=sc.nextDouble(); line but after the double value.

    Example: According to your input,

    12

    4.0 [c=sc.nextLine(); line reads this part. Just after the Double input]

    is the best place to learn and practice coding!

    So try this code. It skips the line which mentioned above.

    public static void main(String[] args) {
           int a;
           double b;
           String c;
    
           Scanner sc=new Scanner(System.in);
           a=sc.nextInt();
           b=sc.nextDouble();
    
           sc.nextLine(); // This line skips the part, after the double value.
    
           c=sc.nextLine();
           System.out.println(a+4);
           System.out.println(b+4.0);
           System.out.println("Hackerrank"+" "+c);
    
    
        }