2015年7月8日 星期三

Java上課練習:投票

練習06_投票
練習07_字串與陣列


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import javax.swing.JOptionPane;

public class VOTE {

    private int num;
    private int[] sums; //每個選項的計票數列
    private boolean exit;
    private String scr;
    private String[] names;//選單選項的字串數列
    private int exitnum;//選單選項字串最後一個

    public void run() {
        do {
            exit = true;
//            顯示選單();
            輸入選項();
            唱票();
            計票();
            顯示結果();
        } while (exit);
    }

    public VOTE(String... names) { //建構子
        this.names = names;
        sums = new int[names.length];//得票數的陣列數量
        exitnum = names.length + 1;

    }

    private void 顯示選單() {
        String s = "";
        for (int i = 0; i < names.length; i++) {
            int a = i + 1;
            s += a + ". " + names[i] + "\n";
        }
        scr = JOptionPane.showInputDialog(s + exitnum + ". EXIT");//視覺化
    }

    private void 輸入選項() {
        do { //當輸入錯誤時,重複進行顯示選單
            this.顯示選單();
            try {
                num = Integer.parseInt(scr);
                if (num > exitnum || num < 1) {
                    JOptionPane.showMessageDialog(null, "錯誤的選項");
                } else if(num==exitnum){
                    exit=false;
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "請輸入數字");
                System.err.println("訊息:" + e.getMessage());
                num=0;//非第一次會記憶num上ㄧ次的值,強制num改回0
            } catch (NullPointerException e) {
                System.err.println("發生null值,物件不存在");
                System.err.println(e.getMessage());
                num=0;//非第一次會記憶num上ㄧ次的值,強制num改回0
            }
        } while (num > exitnum || num < 1);
    }

    private void 唱票() {
        if (num>0 && num<exitnum) {
            int index = num - 1;
            JOptionPane.showMessageDialog(null, names[index] + " 1票");
        }
    }

    private void 計票() {
        if (num>0 && num<exitnum) {
            int index = num - 1;
            sums[index]++;
        }
    }

    private void 顯示結果() {
        String s = "";
        for (int i = 0; i < names.length; i++) {
            int a = i + 1;
            s += a + ". " + names[i] + " 獲得 " + sums[i] + " 票\n";
        }
        JOptionPane.showMessageDialog(null, s);

    }

}

1
2
3
4
5
6
7
8
public class VOTETEST {

    public static void main(String[] args) {

       VOTE Vote = new VOTE("A-lin","Johin","A-mei","JAY","陶吉吉");
       Vote.run();

    }

沒有留言:

張貼留言