Search code examples
javainputstring-concatenation

concatenation not working as expected in java


I expect an output of "I wrote a little code" (in the last line) when I enter "little code" as an input (in the last line), but the output is "I wrote a " This is my code: `

String s = "I wrote a ";
int i = 4;
double j = 7.0; 
Scanner scan = new Scanner(System.in);
String c; int a; double b;
a = scan.nextInt();
b = scan.nextDouble();
c = scan.nextLine();
System.out.println(i + a);
System.out.println(j + b);
System.out.println(s + c);
scan.close();

Solution

  • This piece of code is working fine for me:

    String s = "I wrote a ";
    int i = 4;
    double j = 7.0; 
    Scanner scan = new Scanner(System.in);
    String c; int a; double b;
    a = scan.nextInt();
    b = scan.nextDouble();
    scan.nextLine();
    c = scan.nextLine();
    System.out.println(i + a);
    System.out.println(j + b);
    System.out.println(s + c);
    scan.close();
    

    Was just missing that scan.nextLine() after b = scan.nextDouble();