java - 我想知道为什么我不能将我的文本与代码中的变量连接起来。如何解决此代码?
问题描述
我正在尝试解决字符串连接中的问题但我不明白为什么当我使用“+”运算符时它只给我这样的输出。谁能帮我澄清我的问题是什么。我的代码是
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 是学习和练习编码的最佳场所!
解决方案
问题不在于串联。就是这条线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);
}
推荐阅读
- autodesk-forge - 执行平移或旋转时,模型返回其原始比例
- python - 从数组返回像素位置的索引
- java - Java 正则表达式 Matcher.find() 混淆
- ffmpeg - ffprobe级别和H.264级别有什么区别?
- java - 如何设置 List 类型的变量
类型为 ArrayList 的值 使用构造函数 - c++ - 使用 c++17 CTAD 推导函数对象参数
- c# - Akka.NET .NET Framework - Akka.Remote 配置在启动时总是出错(然后工作正常)
- python - 使用二维随机游走数值解来求解方程。有方法,但没有执行。帖子中的详细信息
- javascript - Eslint 认为一个制表符是 4 个空格
- vagrant - Vagrant 错误:schannel:下一个 InitializeSecurityContext 失败:未知错误(0x80092012)