【问题标题】:Why would this only print the first line?为什么这只会打印第一行?
【发布时间】:2014-02-05 22:48:27
【问题描述】:
import java.util.Scanner;

public class ParseTheTweet {

public static void main(String[] args) {
    // TODO Auto-generated method stub
        Scanner theScanner = new Scanner(System.in);

                    String tweet = "";




        System.out.println("Enter the tweet");
        tweet = theScanner.nextLine();
        System.out.println(tweet);
   }
}

这是我目前拥有的程序,它非常简单,我感觉我做的事情很容易出错。我希望输出变量 tweet 与输入相同,但它只打印第一行。

例如。 输入:

#typ offer; #det free essential supplies 4 evacs pets.; #loc 2323   
55th st, boulder; #lat 40.022; #lng -105.226;       

输出:

 #typ offer; #det free essential supplies 4 evacs pets.; #loc 2323

【问题讨论】:

  • 您为什么期望Scanner.nextLine() 返回多行?
  • 需要做一个while循环,直到扫描仪有EOL
  • 什么扫描仪对象会读取这两行?
  • 您多次致电nextLine,每行一次。它被称为nextLine 而不是allLines
  • 输入总是有 1 或 2 行,虽然我不想询问用户行数,我自动希望它读取一个或两个。

标签: java string class


【解决方案1】:

如果你想读取多行而不是一行,你需要循环调用theScanner.nextLine(),例如:

while (theScanner.hasNextLine()) {
    String tweet = theScanner.nextLine();
    System.out.println(tweet);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2018-07-01
    • 2020-05-19
    相关资源
    最近更新 更多