Java end of file

import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner line = new Scanner(System.in); int counter = 1; while (line.hasNextLine()) { String line = line.nextLine(); System.out.println(counter + ” ” + line); counter++; } } } Task: Each line will contain a non-empty string. Read … Read more

How to detect EOF in Java?

It keeps running because it hasn’t encountered EOF. At end of stream: read() returns -1. read(byte[]) returns -1. read(byte[], int, int) returns -1. readLine() returns null. readXXX() for any other X throws EOFException. Scanner.hasNextXXX() returns false for any X. Scanner.nextXXX() throws NoSuchElementException for any X. Unless you’ve encountered one of these, your program hasn’t encountered … Read more

Why is “while ( !feof (file) )” always wrong

What is wrong with using feof() to control a read loop? For example: [c]#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { char *path = "stdin"; FILE *fp = argc > 1 ? fopen(path=argv[1], "r") : stdin; if( fp == NULL ){ perror(path); return EXIT_FAILURE; } while( !feof(fp) ){ /* THIS IS WRONG */ /* Read … Read more