0
    String s = "Vivek";
    Scanner scan = new Scanner(System.in);
    String s1 = scan.next();
    String sResult = s + s1;
    System.out.println(sResult);

I want to concatenate String S with input string s1 that is "ojha is a Software developer"

I'm not getting the correct output.

Expected Output:
Vivek ojha is a software developer.

Actual output:
Vivek ojha
Vivek
  • 17
  • 3

5 Answers5

0

Do it as @Michal stated:

public static void main(String[] args) {
    String s = "Vivek";
    Scanner scan = new Scanner(System.in);
    // see next line: nextLine()
    String s1 = scan.nextLine();
    String sResult = s + s1;
    System.out.println(sResult);
}
deHaar
  • 11,298
  • 10
  • 32
  • 38
0

Scanner.next() reads a single token. Unless you have configured the Scanner otherwise, this means a string without any whitespace in it.

Either call next() multiple times to get all the number of tokens you want; or use nextLine() to read the entire line.

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
0

Here is your solution

public static void main(String[] args) {
    String s = "Vivek";
    Scanner scan = new Scanner(System.in);
    String s1 = scan.nextLine();
    String sResult = s + " " + s1;
    System.out.println(sResult);
}

Expected Output :

Vivek ojha is a Software developer

Actual Output :

Vivek ojha is a Software developer

Keval Bhatt
  • 122
  • 10
0
import java.util.Scanner;

public class StringConcatenation {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String s1 = "Vivek";
        String s2 = sc.nextLine();
        String s3 = s1 + " " + s2;
        System.out.println(s3);
    }

}

Try this.

Alekya
  • 219
  • 3
  • 15
0

String s = "Vivek";

Scanner scan = new Scanner(System.in);
scan.nextLine();  \\to scan the nextline after the value of s
String s1 = scan.nextLine();  \\to scan inputted string
System.out.println(s + s1);

----This Code worked in HackerRank--------