[JAVA] Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement

It seems like it's just now, but when I first started programming, I'm sure everyone was wondering how to use for statements and while statements properly.

It seems that the general literature in the world often says that ** for statements are used when the number of repetitions is clear **.

However, for me, this explanation didn't come to my mind.

As I was writing the program today, I finally found one point in myself about this difference, so I'll record it here.

Below, it is described in JavaScript.

class Iterator {
  index = 0;
  constructor(list) {
    this.list = list;
  }
  next() {
    return this.list[this.index++];
  }
}

const iterator = new Iterator([1, 2, 3, 4, 5]);

Prepare the ╩╗Iterator` class with the above implementation (actually, you can imagine the file list etc.). Now, suppose you want to describe the process of counting the number of elements while outputting all the elements. Initially, I wrote the following code [^ 1].

let count = 0, item;
while (item = iterator.next()) {
  console.log(item);
  count++;
}
console.log(`Quantity: ${count}`);

To make the code more readable, try rewriting it as follows:

let count, item;
for (count = 0; item = iterator.next(); count++) {
  console.log(item);
}
console.log(`Quantity: ${count}`);

I've rewritten it ... This code is certainly shorter, but doesn't it feel very hard to read?

Perhaps the reason for this is that we

for (A; B; C) {}

Unconsciously when I saw the sentence

For A, while B, do C.

In other words, I think it's because I read ** A, C during B **. For this reason, when you apply the actual formula here, you will feel a strong sense of discomfort if it does not hold as a sentence.

If you want to go a little further, you need to be aware of the statement A, that is, the initialization formula **. As long as the word "for" (about =) is used, B, C, and the sentences in the block are bound by this A part even if you don't like it.

The strange thing about the for statement example above is that the continuation conditional expression and the statements in the block have nothing to do with count, even though the initialization expression is used to initialize the variable count. It was because there was no such thing.

Summary

Of the repetitions that can be expressed by the while statement, the ones that should be expressed by the for statement

I think it can be said that it satisfies.

Extreme example

To put it the other way around, as long as the above rules are met, there are things that can be written using the for statement even if the generally-known "number of iterations is known" is not met. What about the example below?

class Iterator {
  index = 0;
  constructor(list) {
    this.list = list;
  }
  get currentItem() {
    return this.list[this.index];
  }
  next() {
    this.index++;
  }
}

let count = 0;
for (
  const iterator = new Iterator([1, 2, 3, 4, 5]);
  iterator.currentItem;
  iterator.next()
) {
  console.log(iterator.currentItem);
  count++;
}
console.log(`Quantity: ${count}`);

It doesn't feel too strange, right? ?? ??

[^ 1]: In JavaScript, if an index outside the range of the array is accessed, no error will occur and a falsy value of ╩╗undefinedwill be returned. For this reason, thenext method returns one element each time it is executed, and returns ╩╗undefined when all are done.

Recommended Posts

Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement
Compare the speed of the for statement and the extended for statement.
What do you need after all to create a web application using java? Explain the mechanism and what is necessary for learning
Proper use of redirect_to and render
Proper use of Mockito and PowerMock
In order not to confuse the understanding of getters and setters, [Do not use accessors for anything! ]
If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.
[Ruby basics] About the role of true and break in the while statement
(Determine in 1 minute) About the proper use of empty ?, blank? And present?
Proper use of interface and abstract class
I want you to use Enum # name () for the Key of SharedPreference
Do you need a memory-aware implementation of Java?
[For beginners] DI ~ The basics of DI and DI in Spring ~
Until the use of Spring Data and JPA Part 2
Addition of variables in iterative processing in a while statement
Output a list of cron settings for all users.
Until the use of Spring Data and JPA Part 1
What should I do after January 2019 regarding the Java payment issue and Java 8 end of support issue?
# 3 [Note] do ~ while statement
Compare the speed of the for statement and the extended for statement.
Criteria for proper use of render and redirect_to
[For beginners] DI ~ The basics of DI and DI in Spring ~
List of frequently used Java instructions (for beginners and beginners)
Rails: I've summarized the model and database for a moment.
After all, how should I attach the Constraint of ScrollView?
The nth and n + 1st characters of a Ruby string
Convenient use of Map that you do not know unexpectedly
The idea of C # (lambda expression, for statement) to chew
[AWS / S3] After all, how do you upload multiple files?
Aiming for a basic understanding of the flow of recursive processing
What to do if you can't use the rails command
I tried to express the result of before and after of Date class with a number line