【问题标题】:Capturing spaces with Scanner?使用扫描仪捕获空间?
【发布时间】:2014-02-11 09:44:39
【问题描述】:

我有一系列问题被要求创建一副闪存卡。到目前为止,只要问题没有空格,我就可以收集问题和答案。如果问题确实有空格,则跳过答案,但是如果答案有空格,则没有问题。这是我的代码的 sn-p:

System.out.println("数字" + (cards + 1) + "?"); 问题 = in.next(); System.out.println("数字" + (cards + 1) + "?"); 答案 = in.next();

这是一个问题和答案中带有空格的结果输出:

What is the question for number 1?
This is a question
What is the answer for number 1?
What is the question for number 2?
x
What is the answer for number 2?
This is an answer
What is the question for number 3?
X

【问题讨论】:

  • next 之后使用Line

标签: java string java.util.scanner


【解决方案1】:

不要使用next() 方法,而是使用nextLine() 来捕获整行而不是下一个单词:

System.out.println("What is the question for number " + (cards + 1) + "?");
question = in.nextLine();
System.out.println("What is the answer for number " + (cards + 1) + "?");
answer = in.nextLine();

这有帮助吗?

【讨论】:

    【解决方案2】:

    next() 只读取输入直到空格。它无法读取以空格分隔的单词。

    nextLine() 读取输入,包括单词之间的空格(读取到行尾)

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 2015-05-02
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多