无法使用java中的扫描程序从控制台读取最后一行

时间:2015-07-22 18:24:36

标签: java java.util.scanner

这个问题已被提出,但我不清楚答案。 请检查下面的代码。我在控制台中粘贴多行而不按 enter 按钮。 Scanner没有读到最后一行,但是当我按输入时,它会读取它。

我的意见是:

  

2
  4 3
  -1 -3 4 2
  4 2
  0 -1 2 1

输出out out:

  

243-1-34242

当我按回车键时,它显示最后一行。

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    while(scan.hasNext())
    {
        System.out.print(scan.next());
    }
}

请在Eclipse中尝试。

3 个答案:

答案 0 :(得分:0)

请尝试System.out.print(scan.nextLine());

答案 1 :(得分:0)

您也可以使用BufferedReader读取每一行并解析以获取int s(如果需要) -

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line;

while ((line = input.readLine()) != null && line.length()!= 0) {
    String[] ints = line.split(" "); //ints contains all integers only 
                                     //for the current line
}

答案 2 :(得分:0)

我不确定我是否理解这个问题。总之...

您的数据样本在每行末尾包含一个换行符,告诉扫描器该行已结束(最后一行除外)。您应该在最后一行添加换行符,或按Enter键告诉扫描器输入已结束。

相关问题