我想知道为什么我不能将我的文本与代码中的变量连接起来的原因。我该如何解决此代码?

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

我正在尝试解决字符串连接中的问题,但我不明白为什么当我使用“+”运算符时它只给我这样的输出。谁能帮我弄清楚我的问题是什么。我的密码是

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


    } 

我的输入是:

12

4.0

是学习和练习编码的最佳场所!

我的输出是:

16

8.0

黑客排名

但预期输出是:

16

8.0

HackerRank 是学习和练习编码的最佳场所!

当您调用 nextLine() 方法时,扫描仪会将扫描仪移动到下一行。但是 return 是它跳过的那一行。如果您在一行中提供输入
“12 4.0 是学习和练习编码的最佳场所!” 或第一行的“12”,然后按回车 “4.0 是学习和练习编码的最佳场所!” 你会得到想要的结果。

来自 JavaDOC

/** * 将此扫描器推进到当前行之后 returns 输入 * 被跳过。 * * 此方法 returns 当前行的其余部分,不包括任何行 * 末尾的分隔符。位置设置为下一个的开头 * 线。 * *

由于此方法继续搜索输入查找 * 对于行分隔符,它可能会缓冲所有搜索的输入 * 如果不存在行分隔符,则要跳过的行。 * * @return 被跳过的行 * @throws NoSuchElementException 如果没有找到行 * @throws IllegalStateException 如果此扫描器已关闭 */

先只打印c,给出空白值。它没有为 c 赋值。 System.out.println(c);

如果您使用

,问题不在于 + 运算符

System.out.println("Hackerrank"+" "+sc.nextLine());

然后你也会得到预期的输出。

意味着你需要写下面几行: c=sc.nextLine(); c=sc.nextLine(); 然后它将考虑变量 c.

中的预期行

问题不在于串联。这是行 c=sc.nextLine();。 当您使用 c=sc.nextLine(); 时,JVM 在 b=sc.nextDouble(); 行中但在双精度值之后分配值。

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!

所以试试这个代码。它跳过上面提到的行。

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


    }