0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javaのwhile文とfor文

Last updated at Posted at 2020-05-17

while文

while文は一定の処理を自動で繰り返し処理をしたいときに使います。
例えば、1~100までの数字をコンソールに出力したい場合、System.out.println()を100回書くのはコードが冗長になってしまいます。そこで、while文を使います。
繰り返し処理の流れとしては
①変数の初期化
②条件式
③繰り返す処理
④変数の更新
そこからまた
②条件式
③繰り返す処理
④変数の更新
と、繰り返します。

Main.java
while (条件) {
  繰り返す処理;
}

上記のwhile文を使えば繰り返し処理を実行できます。
【例】

Main.java
int x = 3;
  while (x <= 3) {
  System.out.println(x + "位");
  x++;
}

上記はx = 3で変数xを定義しています。x++;はxに1を追加していきます。
変数に1を足していきますので、そうすると4回目の繰り返しでwhileの条件がfalseになり、繰り返し処理が終了します。

【例】

Main.java
int x =5;
  while (x > 0) {
  System.out.println(x);
  x--;
}

上記はが0より大きい場合に繰り返し処理をします。

for文

while文と一緒でfor文も繰り返し処理の1つです。
繰り返し処理の流れとしてはwhile文と一緒で
①変数の初期化
②条件式
③繰り返す処理
④変数の更新
そこからまた
②条件式
③繰り返す処理
④変数の更新
と、繰り返します。
for文

Main.java
for (変数の初期化;条件式;変数の更新) {
  System.out.println(繰り返す処理); 
}

【例】

Main.java
for (int x = 1;x <= 10;x++) {
  System.out.println(x); 
}

上記ように記述すると10回処理を繰り返します。
使うのであればfor文の方が使いやすいですね。

continue

繰り返し処理を終了するにはbreakを使いますが、continueはその周の処理だけをスキップして、次の周を実行します。
【例】

Main.java
for (int x = 1;x <= 10;x++) {
  if(x%5==0) {
  continue;
  }
  System.out.println(x); 
}

上記のように記述すると、5の倍数の周のループを終了し、次のループを実行します。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?