A note of what I learned about loop statements.
Use when you want to repeat the same process a specified number of times using a loop counter or the like. ** ** It is often used for commands such as ** "Output from 1 to 100!" ** Like fizz buzz. It is also compatible with the access of array elements by subscripts, and is also suitable for referencing the contents of an array one by one.
for (Initialization formula;Conditional expression; change expression){
Statement to execute;
Statement to execute;
...
}
(Declaration and initialization of String array)
String[] fighter = {Zero Fighter,Spitfire,Messerschmitt,Lavo chicken};
(Show all the contents of the array arr)
for (int i = 0; i < fighter.length; i++) {
System.out.println("fighter[" + i + "] … " + arr[i]);
}
fighter[0]…Zero Fighter
fighter[1]… Spitfire
fighter[2]… Messerschmitt
fighter[3]… Lavo chicken
** Iterative syntax controlled only by conditional expressions. ** ** Use it properly with the for statement when the number of repetitions such as ** "until the user inputs something" ** is not fixed. In some cases, it may end without moving to make the first judgment.
while(Conditional expression){
Statement to execute
}
//Variable initialization
int i = 1;
//Output numbers from 1 to 10
while (i <= 10){
System.out.println( i );
i++; //If you forget this, an infinite loop will occur, so be careful!
}
1
2
3
4
5
6
7
8
9
10
You can break out of the loop at that point by writing a break statement.
In the if statement etc. ** "When the condition is met, execute the break statement to get out of the loop" **.
for (Initialization formula;Conditional expression; change expression) {
if (Conditional expression to exit the loop) {
break; //Exit the loop if the conditions are met
}
}
Iterative statements that output numbers from 1 to 10 are stopped when break reaches 7.
for (int i = 0; i < 10; i++) {
System.out.println(i);
if (i == 7) {
break;
}
}
1
2
3
4
5
6
7
The continue statement skips further processing at that point.
while (Conditional expression) {
[Process 1]
if (Skip condition) {
continue; //Process 2 is skipped if the conditions are met
}
[Process 2]
}
Outputs numbers from 1 to 10, and skips processing if it is a multiple of 4 (4 and 8).
for (int i = 1; i <= 10; i++) {
if (i % 4 == 0) {
System.out.println("It is a multiple of 4.");
continue;
}
System.out.println(i);
}
1
2
3
It is a multiple of 4.
5
6
7
It is a multiple of 4.
9
10
I think that if you master it, you will be able to express quite complicated things. The infinite loop will be output at a later date.
Recommended Posts