0
0

More than 3 years have passed since last update.

[Java]switch文

Last updated at Posted at 2021-04-07

switch文の構文

switch([評価式]){
    case 1: // "case"と1の間は半角スペースが必要。 
        // 評価式の値が1だったときの処理
        break;
    case 2:
        // 評価式の値が2だった場合の処理
        break;
    default : //"default"と":"の間も半角スペースが必要。
        // 評価式の値が上記のケースに当てはまらなかった場合の処理
        break;
}

上記の評価式の値によって、処理を分岐させることができる。

注意点

1.switch文の評価式は、

  • char
  • byte
  • short
  • int
  • Character
  • Byte
  • Short
  • Integer
  • String
  • 列挙型

のいずれかを戻す式であることある必要がある。例えば、評価式の値としてfloatやdoubleは使用できない。

// 評価式の部分に以下の"abc"や"z"は使用できない。
float abc = 1.4f; // 浮動小数点型なのでコンパイルエラー
double z = 1.2345; //浮動小数点型なのでコンパイルエラー
int i = 123; // OK
String str = abc; // OK

2."break;"を忘れる。
下のコードにおいて、 a = 1の場合。

switch(a){
    case 1:
        System.out.println("abc");
    case 2:
        System.out.println("def");
    default:
        System.out.println("ghi");  //出力結果:"abcdefghi"
}

case 1 、 case 2 、 defaultの処理が実行される。

0
0
1

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