循环扫描输入后无法打印行 - Java

时间:2014-03-01 06:54:08

标签: java io java.util.scanner

为什么不打印'完成'?

public class Main {


public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    while (s.hasNext()) {

        System.out.println(s.nextInt());

    }

    System.out.println("done");

}

}

它打印输入很好,但不打印完成的单词。

编辑 如果我输入在控制台中用空格分隔的整数然后点击回车,它会打印我在一个单独的行上输入的所有整数,但它只是没有在所有这些之后打印完成的单词

修改

这有效...但似乎不是很优雅

public class Main {


public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    int temp;

    while (s.hasNext()) {

        temp = s.nextInt();

        if (temp != -99) {
            System.out.println(temp);
        } else {
            break;
        }

    } 



    System.out.println("done");

}

}

1 个答案:

答案 0 :(得分:1)

您所看到的是Scanner在没有字符的输入流上阻塞,只是等待更多。为了表示流的结尾,流的结尾是'必须发送角色。那是linux上的ctrl-d。

来自java.util.Scanner(http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)的文档。

Both hasNext 
and next methods may block waiting for further input. Whether a hasNext method 
blocks has no connection to whether or not its associated next method will block.

例如,从linux命令提示符

> javac Main.java
> java Main
> 810
810
> 22
22
> foo
java.util.InputMismatchException
> java Main
> 1
1
> ctrl-D
done

另一种测试方法是将行或文件回显到程序中:

> echo 2 | java Main
2
done

编辑:

鉴于以下评论中描述的预期结果;试试下面的内容,它只会读一行。将空格分隔出来,每行回显一次,然后打印完成。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


/**
 *
 */
public class Main {


    public static void main(String[] args) throws IOException {

        String str = new BufferedReader(new InputStreamReader(System.in)).readLine();

        Scanner s = new Scanner(str);

        while (s.hasNext()) {

            System.out.println(s.nextInt());

        }

        System.out.println("done");

    }

}

编辑编辑:清理答案并从评论中获取信息。

相关问题