首页 > 解决方案 > 我想知道为什么我不能将我的文本与代码中的变量连接起来。如何解决此代码?

问题描述

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

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 是学习和练习编码的最佳场所!

标签: javastring-concatenation

解决方案


问题不在于串联。就是这条线c=sc.nextLine();。当您使用c=sc.nextLine();JVM 时,会在该b=sc.nextDouble();行中但在 double 值之后分配值。

示例:根据您的输入,

12

4.0 [c=sc.nextLine();行读取这部分。就在双输入之后]

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

所以试试这段代码。它跳过了上面提到的那一行。

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


    } 

推荐阅读