How to detect EOF in Java?

前端 未结 3 1180
予麋鹿
予麋鹿 2021-01-04 13:57

I\'ve tried some ways to detect EOF in my code, but it still not working. I\'ve tried using BufferedReader, Scanner, and using char u001a to flag the EOF, but still not make

相关标签:
3条回答
  • 2021-01-04 14:16

    You can use try and catch.

    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){
    
    }
    

    Here, when you will give Ctrl+z, Scanner.nextLine() will give you NoSuchElementException. Use this exception as a condition of EOF. To handle this exception use try and catch.

    0 讨论(0)
  • 2021-01-04 14:21

    This is what I did

    Scanner s = new Scanner(f); //f is the file object
    
    while(s.hasNext())
    {
    String ss = s.nextLine();
    System.out.println(ss);
    }
    

    Worked for me

    0 讨论(0)
  • 2021-01-04 14:27

    It keeps running because it hasn't encountered EOF. At end of stream:

    1. read() returns -1.
    2. read(byte[]) returns -1.
    3. read(byte[], int, int) returns -1.
    4. readLine() returns null.
    5. readXXX() for any other X throws EOFException.
    6. Scanner.hasNextXXX() returns false for any X.
    7. Scanner.nextXXX() throws NoSuchElementException for any X.

    Unless you've encountered one of these, your program hasn't encountered end of stream. NB \u001a is a Ctrl/z. Not EOF. EOF is not a character value.

    0 讨论(0)
提交回复
热议问题