Detecting EOF in Java
In this tutorial, we will see how to while
detect EOF( End OF File
) in Java using a loop. We will also discuss developing a program that continues reading content until it reaches the end of a file.
From a programming perspective, EOF is a special type used by developers to continuously read input, whether it is from a file or a keyboard console. This process continues until there is no more data to retrieve.
It is worth mentioning here that the data in the file can be modified or changed at any time. Therefore, it is practically impossible to apply a sentinel control loop on that file.
Therefore, we strongly recommend that you always use file closing loops to mitigate the potential threat of the above issues.
In the following code example, we use the keyboard as the input source.
package sampleProject;
import java.util.*;
import java.util.Scanner;
public class Codesample {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int total_ages = 0;
int age;
while (console.hasNext()) {
age = console.nextInt();
total_ages = total_ages + age;
}
System.out.println("Total ages are:" + total\_ages);
}
}
Output:
99
90
88
Ko
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at sampleProject/sampleProject.Codesample.main(Codesample.java:15)
We start by declaring and initializing an object of the Scanner class. After that, I have declared some other variables to use in our code.
You may have noticed that we use console.hasNext()
as the loop iteration condition. We already know that the console is an object of our input class Scanner.
On the other hand, hasNext()
is a predefined method in the input class Scanner. This expression returns true only if there is an integer input. Otherwise, it returns false.
Compile this code on your own and see the output. It is clear from the output that our program continues to read the data until we provide the wrong input type. In this case, the program throws an input mismatch exception.
File as input source
In another example, we use an end-of-file controlled while loop to continuously read data from a file.
Suppose we want Students\_Result.txt
to read all the data from the file . The file contains the names of students followed by their exam scores.
Our goal in this program is to output a file that displays the student's name, test score, and grade.
package sampleProject;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.Scanner;
public class Codesample {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
// declare file name as an input object
Scanner inputFile = **new** Scanner(**new** FileReader("Students\_Result.txt"));
// declare the output object that stores data we want to display
PrintWriter outputFile = **new** PrintWriter("Students\_Record.txt");
// Declare variable to store first name and last name
String firstName, lastName;
// declare variable to store score
double score;
// declare variable to store student's grad
char grade = ' ';
// declare and initialize counter variable
int counter = 0;
// continue reading data from the file until the loop reaches end of file
while (inputFile.hasNext()) {
// read first name from the provided file
firstName = inputFile.next();
// read last name from the file
lastName = inputFile.next();
// read score of the students from the filee
score = inputFile.nextDouble();
// increment counter variable
counter++;
// To evaluate grade of the students, we are using the switch statemet
switch ((int) score / 10) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
grade = 'F';
break;
case 6:
grade = 'D';
break;
case 7:
grade = 'C';
break;
case 8:
grade = 'B';
break;
case 9:
case 10:
grade = 'A';
break;
default:
outputFile.println("Your score does not meet our criteria");
}
// Display retrieved data using the outputFile object we have declared earlier
outputFile.println(firstName + " " + lastName + " " + score + " " + grade);
}
// If no data is found in the output file
if (counter == 0)
outputFile.println("There is not data in your input file");
// close output file upon reading all the data from it.
outputFile.close();
}
}
Output:
Waleed Ahmed 89.5 B
Bob Alice 90.0 A
Khan Arshad 100.0 A
Waqas Jameed 65.5 D
Danish Taimoor 70.5 C
Muaz Junaid 80.5 B
John Harris 88.0 B
Compile and run this program on your system to see what happens.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Get resource URL and content in Java
Publish Date:2025/04/14 Views:97 Category:Java
-
getResource() This tutorial will demonstrate how to use the function to get the resource URL and read the resource file in Java . getResource() Use the function to get the resource URL in Java We will use the method in Java getResource() to
Getting the host name in Java
Publish Date:2025/04/14 Views:78 Category:Java
-
In this tutorial, we will see how to get the IP address and host name using Java API. InetAddress Get the host name in Java using The package java.net contains classes for handling the IP address and host name of the current machine InetAdd
Get the IP address of the current device in Java
Publish Date:2025/04/14 Views:53 Category:Java
-
An Internet Protocol (IP) address is an identifier for each device connected to a TCP/IP network. This identifier is used to identify and locate nodes in the middle of communication. The IP address format, such as 127.0.0.0, is a human-read
Generate a random double value between 0 and 1 in Java
Publish Date:2025/04/14 Views:153 Category:Java
-
This article will introduce three methods to generate double random values between 0 and 1 of primitive types. To demonstrate the randomness of the generated values, we will use a loop to generate ten random double values betwee
Setting the seed of a random generator in Java
Publish Date:2025/04/14 Views:62 Category:Java
-
A seed is a number or vector assigned to a pseudo-random generator to generate the desired sequence of random values. If we pass the same seed, it will generate the same sequence. We usually assign the seed as the system time. In this way,
Switching on enumeration types in Java
Publish Date:2025/04/14 Views:96 Category:Java
-
This article explains how to use enum in Java . We will use statement switch with enum in two ways . switch In Java, we use traditional switch and case to perform enumeration operations. switch In this example, we SwitchEnum create an enume
How to delay for a few seconds in Java
Publish Date:2025/04/14 Views:131 Category:Java
-
This tutorial explains how to create program delays in Java and gives some sample code to understand it. There are several ways to create a time delay, such as TimeUnit.sleep() ,, ScheduleAtFixedRate() etc. Thread.sleep() Let's look at an e
How to Convert Hashmap to JSON Object in Java
Publish Date:2025/04/14 Views:112 Category:Java
-
This article explains how to convert a Hashmap to a JSON object in Java. We will see a detailed example of creating a hashmap and then converting it to a JSON object. Hashmap and JSON are both very commonly used by developers as they help u
How to sort a Map by value in Java
Publish Date:2025/04/14 Views:171 Category:Java
-
This tutorial explains how to Mapkey, value sort pairs by value in Java and lists some sample codes to understand it. There are several ways to Map sort . Here we use sort() the , sorted() method, and Comparator interface. Let's look at an