【问题标题】:concatenation not working as expected in java [closed]连接在java中没有按预期工作[关闭]
【发布时间】:2017-02-25 15:29:24
【问题描述】:

当我输入“小代码”作为输入(在最后一行)时,我希望输出“我写了一个小代码”(在最后一行),但输出是“我写了一个” 这是我的代码:`

String s = "I wrote a ";
int i = 4;
double j = 7.0; 
Scanner scan = new Scanner(System.in);
String c; int a; double b;
a = scan.nextInt();
b = scan.nextDouble();
c = scan.nextLine();
System.out.println(i + a);
System.out.println(j + b);
System.out.println(s + c);
scan.close();

【问题讨论】:

  • 您确定您确实在控制台中输入了某些内容,并且这是导致您的问题的代码吗? 您需要按回车键/换行符nextLine 才能工作。
  • 我觉得没问题。
  • 你在使用在线编译器吗?
  • 是的,这是代码,我正在使用在线编译器
  • @MouadELFakir Ideone 对我来说很好用(快速复制粘贴到默认主方法中:P) OP:你确定代码 真的在打印 "I wrote a" 和退出,还是只是因为nextLine 停止而没有执行第二次打印?

标签: java input string-concatenation


【解决方案1】:

这段代码对我来说很好用:

String s = "I wrote a ";
int i = 4;
double j = 7.0; 
Scanner scan = new Scanner(System.in);
String c; int a; double b;
a = scan.nextInt();
b = scan.nextDouble();
scan.nextLine();
c = scan.nextLine();
System.out.println(i + a);
System.out.println(j + b);
System.out.println(s + c);
scan.close();

只是在 b = scan.nextDouble(); 之后缺少那个 scan.nextLine();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多