Loops

jr·2021년 4월 14일

I can use a For loop to read all lines in a given file until EOF.

Scanner scan = new Scanner();
//don't forget to declare Scanner.

for (int i=1; scan.hasNext(); i++){
	//code block;
}

How did the above work?

According to this documentation on For loops, in a For loop,
for (statement 1, statement 2, statement 3){},
statement 1 is executed before the code block runs, statement 2 is the condition that must be met for the code block to run, and statement 3 is executed after the code block is run.

Does Java support a While Loop?

My first guess was that I would have to use a While loop. The only reason I went with a For loop instead was that I didn't know the syntax for While loops in Java. But a quick Google search and some patience were all I needed. And here it is, the syntax for a While loop:
while(condition_statement){}

To read lines in a file until the EOF using a While loop, do the following:

while(scan.hasNext()){
   //code block;
}

Till next time...

profile
My journey starts from Googling "What is a computer language?"

0개의 댓글