【问题标题】:What is the difference between .nextLine() and .next()? [duplicate].nextLine() 和 .next() 有什么区别? [复制]
【发布时间】:2016-06-20 10:30:49
【问题描述】:

我正在制作一个程序并使用用户输入。当我得到一个字符串时,我总是使用.nextLine(),但我也使用过.next(),它做同样的事情。有什么区别?

Scanner input = new Scanner(System.in);
String h = input.nextLine();
String n = input.next();

有什么区别?

【问题讨论】:

标签: java string java.util.scanner user-input


【解决方案1】:

长话短说:

nextLine - 读取整行。

下一个 - 读取到第一个空格。

举个例子:

// Input : Barack Obama
String st = in.next(); // st holds the String "Barack"
String st2 = in.nextLine(); //st2 holds the String "Barack Obama"

【讨论】:

  • 我也在 for 循环中使用它们,并注意到如果你在字符串之前输入一个数字,那么它会跳过 nextLine 并且不会跳过下一个。这是为什么呢?
猜你喜欢
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
  • 2013-02-07
  • 2015-11-23
  • 2013-02-13
  • 2011-04-26
  • 2016-09-24
相关资源
最近更新 更多