End of file while loop in Java
Coding River
End-of-file while loop in Java
Hi and welcome back to this channel, In today’s video, I will show you how to use one other form of a while loop which is called the End-of-File while loop. And I will also show you with a practical example, how to design a program that will you to read the content of the file until there are no more data to read Actually, the End-of-file loop is a kind of loop that is used to continually read input value, be it from a keyboard or from a file, until there are no more data values to read
It is important to know how to use this form of a loop, because you may be developing a program where you would use a file as the source of input for your application Then, as you know data in a file can be dynamic and altered or modified at any moment So, it is not a good idea to apply a sentinel-controlled loop over that file For the simple reason that someone may accidentally erase the sentinel variable Or even modify the content of the file especially when many people are working on the same project This can lead to errors and eventually waste time
So, as you might have understood, in such a situation, using an End-of-file loop is the best thing to do
A very important note here is that the form of an End-of-file while loop depends on the type of object you use to input data in a program
Here on the screen is a typical example of an End-of-file while loop that uses the keyboard as the source of input
static Scanner console = new Scanner(System.in);
int total_price = 0; int price;
while (console.hasNext()) { price = console.nextInt(); total_price = total_price + price; }
Here is what you need to note from this portion of code
I started by declaring and initializing the input object, that I called console
After that, I have also declared the various variables that will be used in the program, here total_price and price
Notice that I am using the expression console.hasNext() as the loop condition We already know what console is, that’s representing my input object And hasNext() here, is a method that belongs to the class Scanner This expression will return true if there is an input value otherwise it will return false
Now, let’s run the code and see what happens
Now, in our second example, we are going see how to write an End-of-file-controlled while loop that uses a file as the source of input
Let’s suppose that we are given a file consisting of students’ names and their test scores Each line of the file is made up of the student name followed by the test score So, we want to build a program that would output each student’s name followed by the score and the grade
To begin, you have to make sure that you have saved the input file correctly And I need to declare the input object like this Scanner input_file = ... https://www.youtube.com/watch?v=pVsXg8Br-nU
21988930 Bytes