【问题标题】:Understanding reading String using scanner [duplicate]了解使用扫描仪读取字符串 [重复]
【发布时间】:2017-01-10 07:00:57
【问题描述】:

我想读取一个 int、double 和 string 并将每一个添加到一个变量中,但我无法读取字符串。

int i = 4;
double d = 4.0;
String s = "My name is ";   
Scanner scan = new Scanner(System.in);
int i2 = scan.nextInt();
double d2 = scan.nextDouble();
String s2 = scan.nextLine();        
System.out.println(i+i2);
System.out.println(d+d2);
System.out.println(s + s2);
scan.close();

我的理解是scan.nextLine() 读取一个字符串,但它只是跳过它。 scan.next() 只读取第一个单词。 如果我在String str2 = scan.nextLine(); 之前添加scan.nextLine(); 它可以正常工作,但我不知道为什么

【问题讨论】:

标签: java


【解决方案1】:

输入

 2.4
 "Some String"

当您使用 nextDouble 时,仅选择 2.4 而不是 EndOfLine(在 2.4 之后和 "Some String". 之前)。 因此,您的代码使用 2 nextLine() 工作。

你也可以使用

int i2 = Integer.parseInt(scan.nextLine());
double d2 = Double.parseDouble(scan.nextLine());
String str2 = scan.nextLine();  

【讨论】:

  • The method parseInt(String) in the type Integer is not applicable for the arguments (int)
  • 感谢@joc,已编辑:)
  • @Lokesh Agrawal 知道了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-07-21
  • 2019-12-09
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
相关资源
最近更新 更多