LoginSignup
0
0

More than 1 year has passed since last update.

Javaを基本からまとめてみた【分岐処理・繰り返し処理】

Last updated at Posted at 2023-03-07

構造化プログラミング

構造化プログラミングとは、下の構造を組み合わせてプログラムを書くことをいう。

image.png

if文

if(条件式){
  『処理1』
} else {
 『処理2』
}
  • 何方かの処理しか実行されない
  • else以降は省略可
  • 処理が1つの時は{ }を省略可
Sample.java
public class Branch {
    public static void main(String[] args) {
    int price = Integer.parseInt(args[0]);
    double rate = 0.10; //消費税率:10%
    int discount, amount;
    
        if (price >= 3000) { //値引額の設定
            discount = 300;
        } else {
            discount = 300;
        }
    amount = (int)((price - discount) * (1 + rate));
    System.out.println("値引金額:" + discount + "円"); 
    System.out.println("税込金額:" + amout + "円"); 
    }
}

else-if文

if(条件式){
  『処理1』
} else if(条件式2){
 『処理2』
} else {
 『処理3』
}
  • 条件式は上から順に判定
Sample.java
public class Branch {
    public static void main(String[] args) {
    int price = Integer.parseInt(args[0]);
    double rate = 0.10; //消費税率:10%
    int discount, amount;
    
        if (price >= 3000) { //値引額の設定
            discount = 300;
        } else if (price >= 3000){
            discount = 300;
        } else {
            discount = 0;
        }

    amount = (int)((price - discount) * (1 + rate));
    System.out.println("値引金額:" + discount + "円"); 
    System.out.println("税込金額:" + amout + "円"); 
    }
}

switch文

image.png

if(条件式1){
  case 値1:
  『処理1』
  break;
  case 値2:
 『処理2』
  break;
  default:
 『処理3』
}
  • 式は『byte』『short』『int』『char』のみ

  • 式の値によって処理の開始位置が決まる

  • breakは{]を抜ける

Sample.java
public class Branch {
    public static void main(String[] args) {
    int num = Integer.parseInt(args[0]);
    switch(num) {
   case1:
     System.out.println("入園料金:8,400円"); 
     break;
   case2:
     System.out.println("入園料金:7,000円"); 
     break;
   case3:
     System.out.println("入園料金:5,000円"); 
     break;
    dafault: 
      System.out.println("1:一般、2:中・高校生、3:小学生・幼児"); 
      }
   }
}

while文

image.png

while(条件式){
  『処理』
}
int i = 0;
while(i < 3){
System.out.println("i =" +i); 
i ++;
}

for文

image.png

for(式1; 条件式:式2)
  『処理』
}
for(int i = 0; i < 3; i++){
System.out.println("i =" +i); 
}

参考サイト

Javaの分岐処理:if、else-if、switchの書き方・使い分けを初心者向けに解説!【Java入門講座】2-8 分岐処理

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