如何在Java中检测EOF?

时间:2016-04-09 11:06:11

标签: java eof

我已经尝试了一些在我的代码中检测EOF的方法,但它仍然无效。 我尝试过使用BufferedReader,Scanner,并使用char u001a来标记EOF,但对我的代码仍然没有任何意义。 这是我的最后一段代码:

    Scanner n=new Scanner(System.in);
    String input;
    int counter=0;

    while(n.hasNextLine())
    {
        input=n.nextLine();
        char[] charInput=input.toCharArray();
        for (int i = 0; i < input.length(); i++) {
            if(charInput[i]=='"')
            {
                if(counter%2==0)
                {
                    System.out.print("``");
                }
                else
                {
                    System.out.print("''");
                }
                counter++;
            }
            else
            {
                System.out.print(charInput[i]);
            } 
        }
        System.out.print("\n");
    }

该程序应该在已经达到EOF时停止,但我不知道为什么,由于某些原因它继续运行并导致运行时错误。 请帮忙。 顺便说一下,我是新来的,对不起,如果我的问题不是很清楚, 谢谢你:)

3 个答案:

答案 0 :(得分:10)

它一直在运行,因为它没有遇到EOF。在流结束时:

  1. read()返回-1。
  2. read(byte[])返回-1。
  3. read(byte[], int, int)返回-1。
  4. readLine()返回null。
  5. readXXX()针对任何其他X投掷EOFException
  6. Scanner.hasNextLine()返回false。
  7. Scanner.nextLine()抛出NoSuchElementException
  8. 除非您遇到其中一个,否则您的程序没有遇到流结束。 NB \u001a是Ctrl / z。不是EOF。 EOF不是字符值。

答案 1 :(得分:0)

这就是我做的事情

Scanner s = new Scanner(f); //f is the file object

while(s.hasNext())
{
String ss = s.nextLine();
System.out.println(ss);
}

为我工作

答案 2 :(得分:-2)

您可以使用尝试并捕获

Scanner n=new Scanner(System.in);
String input;
int counter=0;
input=n.nextLine();
try{
    while(input!=null)
    { 
        char[] charInput=input.toCharArray();
        for (int i = 0; i < input.length(); i++) {
            if(charInput[i]=='"')
            {
                if(counter%2==0)
                {
                    System.out.print("``");
                }
                else
                {
                    System.out.print("''");
                }
                counter++;
            }
            else
            {
                System.out.print(charInput[i]);
            } 
        }
        System.out.print("\n");
        input=n.nextLine();
    }
}catch(Exception e){

}

在这里,当您提供 Ctrl + z 时,Scanner.nextLine()将给您NoSuchElementException将此例外用作EOF的条件。要处理此异常,请使用try and catch。