LoginSignup
0

More than 3 years have passed since last update.

(メモ)Java for文

Last updated at Posted at 2019-08-27

for文での繰り返し処理

ループ処理・繰り返し処理と呼ばれる処理をまとめます。
Javaでは次の3つが用意されています。

  • for文
  • while文
  • do文(do while)

記述式

  • for(初期値の設定;継続条件;値の操作){処理}

  • while(条件){処理}

  • do{処理}while(条件);

コードを書いてみよう

数字を入力し、その個数だけ*を表示するプログラム


import java.util.Scanner;

class PutKome {

  public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);

    System.out.print("何個お米を表示しますか:");
    int n = stdIn.nextInt();

    for (int i = 0; i < n; i++) {
      System.out.print('*');
    }
    System.out.println();
  }
}

【結果】

何個*を表示しますか:5
*****

解説

  1. nの入力値を受け取る
  2. [初期値]iに0を代入する
  3. [継続条件]iがn未満?
  4. Yes:*を出力、[操作]i+1…Noになるまで繰り返す/No:改行

1566876503855.jpg

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