このプログラムは
長方形1の面積が長方形2の面積よりも大きい場合、赤く塗りつぶした二つの長方形を表示
長方形1の面積が長方形2の面積よりも小さかった場合、青く塗りつぶした二つの長方形を表示する
というようなものです。
JavaAppletで実行しています。
下のコードを見てもらった際に、実行した結果は良いのですが
g.fillRect(20, 30, width1, height1);
g.fillRect(120, 30, width2, height2);
という長方形を描く処理が、if文の中に入っており
これをif文の外にだして一つにまとめるべきと言われました。
if文の外に出して、まとめる。というのが全くわかりません。
どうやって一つにまとめたら良いのでしょうか?
lang
1import java.applet.Applet; 2import java.awt.Color; 3import java.awt.Graphics; 4public class DrawRect extends Applet{ 5 public void paint(Graphics g){ 6 7 int width1 = 90;//長方形1の幅 8 int height1 = 150;//長方形1の高さ 9 int width2 = 50;//長方形2の幅 10 int height2 = 85;//長方形2の高さ 11 int area1 = (width1 * height1);//長方形1の面積 12 int area2 = (width2 * height2);//長方形2の面積 13 14 if(area1 > area2){//長方形1の面積が長方形2の面積より大きい場合 15 g.setColor(Color.red);//赤色を設定 16 g.fillRect(20, 30, width1, height1); 17 g.fillRect(120, 30, width2, height2); 18 } 19 else if(area1 < area2){//長方形1の面積が長方形2より小さい場合 20 g.setColor(Color.blue);//青色を設定 21 g.fillRect(20, 30, width1, height1); 22 g.fillRect(120, 30, width2, height2); 23 24} 25 } 26} 27
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/06/12 23:58