Search code examples
javastringstring-concatenation

How to scan a string in java and then concate it with other string?


The code is not scanning the second string form user. It just prints 'Hello' second string is not printed.

package online_questions;
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scan = new Scanner(System.in);
    int i = 4;
    double d = 4.0;
    String s = "Hello ";
    int a = scan.nextInt();
    double b = scan.nextDouble();
    String c = scan.nextLine();
    System.out.println(i+a);
    System.out.println(d+b);
    System.out.println(s + c);
}

}


Solution

  • after

    double b = scan.nextDouble();
    

    add

    scan.nextLine();
    

    The methods nextInt nextDouble etc doens't move to the next line automatically. So you need to call them explicitely.