LoginSignup
0
0

More than 5 years have passed since last update.

for文で混乱してきた人へ

Last updated at Posted at 2016-12-02
for(int i=0;i<xxx.length;i++){

}

とforの入れ物を書いたものの中身が書けない人向け

こういうときはforを使わない場合を考えてコードを書いてみるといいかもしれません

たとえば、配列pricesに5つの値を入れて、1000以上ならsell,未満なら buyと出力するコードを考える時、

int prices[] ={699,249,1200,30,5000};

if(price[0]=>1000){
    System.out.println("sell");
} else {
    System.out.println("buy");
}

if(price[1]=>1000){
    System.out.println("sell");
} else {
    System.out.println("buy");
}

if(price[2]=>1000){
    System.out.println("sell");
} else {
    System.out.println("buy");
}

このように書いていくうちに繰り返し部分そうでない部分が見えてくるので(この場合は 0,1,2)そこを i に書き換えてあげます。

for(int i=0;i<price.length;i++){
    if(price[i]=>1000){
        System.out.println("sell");
    } else {
        System.out.println("buy");
    }
}

以上。頭が痛くなってきたら試してみてください。

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