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?

Java学習メモ⑤ 配列と繰り返し処理

0
Posted at

配列の指定

int[] prices = {100, 200, 300};
String[] names = {"みかん", "リンゴ", "バナナ"};
  • int[] は「int 型の配列」
  • {}の中にカンマ区切りで指定

配列の要素

int[] prices = {100, 200, 300};

System.out.println(prices[0]);
  • 0は最初の要素である100のこと。
System.out.println(prices.length);
  • lengthは要素の長さ(数)
  • prices[3]にアクセスすると存在しないので
    ArrayIndexOutOfBoundsException エラーが出る

for文(繰り返し処理・ループ)

for (int price : prices) {
    System.out.println(price);
}
  • for (int price : prices)
    ⇒意味:prices配列の中の要素をint price変数に入れてそれぞれ処理する
  • :は「~の中のそれぞれについて」

for文の例

public class Main{
    public static void main(String[] args){
        int[] prices = {100, 200, 300};

        for(int price : prices){
            System.out.println(price);
        }
    }
}
結果
100
200
300
  • prices配列から要素を取り出し、price変数に代入している
  • 3つの要素があるので3回繰り返ししている

レジプログラムの例

public class Main{
    public static void cashier(int[] prices){
        int total = 0;
        for(int price : prices){
            total += price;
        }
        System.out.println((int)(total * 1.1) + "円");
    }

    public static void main(String[] args){
        cashier(new int[]{100, 200, 300});
        cashier(new int[]{1000, 2000, 1500});
    }
}
結果
600円
1750円
  • for ⇒繰り返し処理
  • 引数にint[] ⇒pricesを書くことでintの配列を受け取れる
  • new int[]{} ⇒という書き方はメソッドの引数に配列を渡す書き方
  • 繰り返し(ループ)処理の外にtotal = 0の初期化を必ず書く
    ⚠️書き忘れるとコンパイルエラーになる
    ⚠️ループ内で書くと毎回リセットされてしまってループの中で数字が累積しない
  • for(int price : prices) 左記の型を必ず指定する
  • メソッドに配列を直接渡すとき、new int[] が必要
0
0
0

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?