字符串与输入字符串的连接

时间:2018-07-05 11:12:00

标签: java string

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

我想将字符串S与输入字符串s1(即“ ojha是软件开发人员”)连接起来

我没有得到正确的输出。

Expected Output:
Vivek ojha is a software developer.

Actual output:
Vivek ojha

6 个答案:

答案 0 :(得分:0)

按照@Michal所述进行操作:

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);
}

答案 1 :(得分:0)

Scanner.next()读取单个令牌。除非您另外配置了扫描程序,否则这意味着其中没有任何空格的字符串。

多次调用next()以获取所需的所有令牌数量;或使用nextLine()阅读整行。

答案 2 :(得分:0)

这是您的解决方案

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);
}

预期输出:

Vivek ojha是一名软件开发人员

实际输出:

Vivek ojha是一名软件开发人员

答案 3 :(得分: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);
    }

}

尝试一下。

答案 4 :(得分:0)

这似乎是我在HackerRank上遇到的问题。我决定解锁该问题的最佳解决方案之一,该解决方案与我的解决方案相同,但仍无法在我的计算机上使用。

答案 5 :(得分: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);

----此代码在HackerRank中工作--------