import java.awt.*; import javax.swing.*; import java.util.Random; // 乱数を使うのでRandomクラスを呼び出し public class Ex5_4 extends JPanel { public void paintComponent(Graphics g) { Random rnd = new Random(); // Randomクラスの宣言・インスタンス生成 int[] x = new int[80]; int[] y = new int[80]; int pt = 80; x[0] = 0; // 初期位置 x座標 0 y[0] = 200; // 初期位置 y座標 200 for (int i=1; i<80; i++) { x[i] = x[i-1] + 5; y[i] = y[i-1] + 10*(rnd.nextInt(3)-1); // *.nextInt(3) は0,1,2を各1/3の確率で出す } g.drawPolyline(x, y, pt); g.drawString("ランダム・ウォークだよ", 50, 50); } public static void main(String[] args) { JFrame app = new JFrame(); app.add(new Ex5_4()); app.setSize(500, 400); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setVisible(true); } }