Java Array


學校中的一篇日誌..
主要將一個原來用 switch 的檢查月份日數的東西改為了 array 方法..
Java 和 VB.NET 的寫法有點類似 = = ..?

Array 的方法 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import javax.swing.JOptionPane;

public class test {
public static void main(String args[]) {

String m = JOptionPane.showInputDialog(null, "Enter a month");
String ys = "";

String[] m_s = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
int[] m_d = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

if (m.equals("2")) {
int y = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a year"));
ys = " and year " + y;

if ( (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) ) m_d[1] = 29;
}

int t = Integer.parseInt(m) - 1;

JOptionPane.showMessageDialog(null, "The number of days on month " + m_s[t] + ys + " is " + m_d[t]);
System.exit(0);
}
}

原來的 Switch 方法 :

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
import javax.swing.JOptionPane;

public class a3 {
public static void main(String args[]) {

String m = JOptionPane.showInputDialog(null, "Enter a month");
String tmp = "28";
String shortName, ys = "";

if (m.equals("2")) {
int y = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a year"));
ys = " and year " + y;

if ( (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) ) tmp = "29";
}

switch(Integer.parseInt(m)) {
case 1: shortName = "Jan"; tmp = "31"; break;
case 2: shortName = "Feb"; break;
case 3: shortName = "Mar"; tmp = "31"; break;
case 4: shortName = "Apr"; tmp = "30"; break;
case 5: shortName = "May"; tmp = "31"; break;
case 6: shortName = "Jun"; tmp = "30"; break;
case 7: shortName = "Jul"; tmp = "31"; break;
case 8: shortName = "Aug"; tmp = "31"; break;
case 9: shortName = "Sep"; tmp = "30"; break;
case 10: shortName = "Oct"; tmp = "31"; break;
case 11: shortName = "Nov"; tmp = "30"; break;
default: shortName = "Dec"; tmp = "31"; break;
}

JOptionPane.showMessageDialog(null, "The number of days on month " + shortName + ys + " is " + tmp);
System.exit(1);
}
}