PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] How to detect EOF in Java?

 October 29, 2022     eof, java     No comments   

Issue

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 any sense to my code. Here is my last code :

    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");
    }

The program supposed to stopped when it's already reached the EOF, but I don't know why, for some reasons it keeps running and result a runtime error. Please help. By the way I'm new here, sorry if my question is not really clear to be understood, Thank you before :)


Solution

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.



Answered By - user207421
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing