LoginSignup
0
0

More than 1 year has passed since last update.

Javaのswitch文について

Last updated at Posted at 2022-05-21

Javaのswitch文についてどうも上手くいかなかったので、備忘録として記録。

ケーキと個数をコマンドライン引数で渡してやると、その合計金額が表示されるというプログラムをfor文とswitch文を駆使して作る。

まずは商品の情報を変数に代入。

//商品名と価格を変数に代入
		String cake1 = "ショートケーキ";
		int cakePrice1 = 320;
		String cake2 = "モンブラン";
		int cakePrice2 = 350;
		String cake3 = "チョコレートケーキ";
		int cakePrice3 = 370;
		String cake4 = "いちごのタルト";
		int cakePrice4 = 400;
		String cake5 = "チーズケーキ";
		int cakePrice5 = 300;

次に入力したケーキがいくらなのかをswitch文で取り出し、それをfor文で繰り返し足していく。

String order = "";
		for(int i = 0; i < args.length; i += 2) {
			order = args[i];
			price = 0;     
			switch(order) {
				case cake1:
					price = cakePrice1 * Integer.parseInt(args[i+1]);
				    price += price;
				    break;
				case cake2:
					price = cakePrice2 * Integer.parseInt(args[i+1]);
				    price += price;
				    break;
				case cake3:
					price = cakePrice3 * Integer.parseInt(args[i+1]);
				    price += price;
				    break;
				case cake4:
					price = cakePrice4 * Integer.parseInt(args[i+1]);
				    price += price;
				    break;
				case cake5:
					price = cakePrice5 * Integer.parseInt(args[i+1]);
				    price += price;
				    break;
			}
		}

だが上記を実行してもcase 式は定数式でなければなりませんとエラーが出てしまう。

結果としては変数の宣言が間違っていた。
定数式でないといけないということは、変更不可にしないといけないということ。
つまり下記の通りに変数を宣言し直す。

        final String CAKE1 = "ショートケーキ";
		int cakePrice1 = 320;
		final String CAKE2 = "モンブラン";
		int cakePrice2 = 350;
		final String CAKE3 = "チョコレートケーキ";
		int cakePrice3 = 370;
		final String CAKE4 = "いちごのタルト";
		int cakePrice4 = 400;
		final String CAKE5 = "チーズケーキ";
		int cakePrice5 = 300;

これでエラーは解消された。

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