2014程式設計二講義(java)aiplab.net/2014java.pdf整數亂數的範圍: ‐...
TRANSCRIPT
程式設計(二)
‐2‐
內容
第一講:使用 Eclipse 寫 Java 程式 ......................................................................................... 3
第二講:編寫 Java 程式的演算法流程 .................................................................................. 9
第三講:Java 檔案輸出入 ..................................................................................................... 12
第四講:Java 的亂數 ............................................................................................................. 15
第五講:樂透對獎 ................................................................................................................. 18
第六講:JSP 程式 ................................................................................................................... 22
程式設計(二)
‐4‐
Step 3: 下載安裝 Eclipse,開啟 Eclipse
http://ftp.asia.edu.tw/ftp/eclipse/eclipse/downloads/drops4/R-4.1-201106201631/eclipse-SDK-4.1-win32.zip
Step 4: 建立 Java 專案
程式設計(二)
‐7‐
Step 8: 以命令列執行
程式碼
1
2
3
4
5
6
7
8
package asia.edu.tw;
import java.io.*;
public class Ex1Class {
public static void main(String[] args) {
int nID = 100111234;
System.out.printf("My name: %s ID: %9d\n", "John", nID );
}
}
Note1: 註解
Java 的程式有二個地方是非程式碼的注解(Comment)。
(1) 由 “/*” 及 “*/” 所圈起來的文字。
(2) “//”之後的那一行剩下的文字
註解和程式的編譯及執行一點關係都沒有。只是給寫程式的人看,了解程式的目
的,每一個敘述的作用或修改的原因等等。
Note2: 基本資料型別
Java 語言有以下的幾種主要資料型別:
名稱 說明 例
String 字串 String str = "abc";
long 長整數 long myIntLong;
int 一般整數 int x,y,z;
float 單精度浮點數 float realNum;
double 雙精度浮點數 double realValue;
Note3: 基本輸出
Java 的 printf()函數的輸出格式化參數型態,可以包括下列各種數值。
程式設計(二)
‐8‐
%d 十進位整數 %x 16 進位整數(英文字母小寫)
%c 字元 %X 16 進位整數(英文字母大寫)
%o 8 進位整數 %f 小數表示浮點數
%u 十進位正整數 %e 科學表示浮點數(指數小寫)
%s 字串 %E 科學表示浮點數(指數大寫)
進一步我們可以控制格式化輸出格式為:
%[flags] [width] [.precision] type。
type 是如說明六所列的英文字母。其它的參數如下:
[flags] 旗標值可以為 ‐ + #及空白。
[width] 欄位寬度。
[.precision] 數值的精確度,也就是小數要有幾個位元。
程式設計(二)
‐10‐
Step 4: 進行運算及判斷
Step 6: 輸出結果
Step 7: 執行
程式碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Scanner;
public class Ex2Class {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.printf("Input ID:");
int nID = sc.nextInt();
int even = 0, odd = 0, digits=0;
int num=nID;
while (num >0)
{
digits++;
if (num%2==0)
even++;
num /=10;
}
odd = digits - even;
程式設計(二)
‐11‐
17
18
19
20
System.out.printf("My ID: %9d -- %d digits %d
odd nums %d even nums\n", nID, digits, odd, even);
}
}
Note1: while 迴圈
while (num>0) 及其後面 4 行的敘述是一種迴圈表示式。while‐loop 的作用是說,
如果 while()括符內的條件成立的話,則下面的敘述就反覆進行。為了讓迴圈結
束,我們必須有變數控制迴圈進行。如果,少了 num /=10;這一行,迴圈會無限執
行下去。
Note2: 基本運算
num%2 這個敘述中的百分比符號是取餘數的運算子。Java 語言除了常見的數學
四則運算加減乘除(符號為 “+” “‐”“*”及“/”)之外,還有以下運算子。
符號 說明 優先權
* / % 乘除法運算子 3
+ – 加減法運算子 4
<< >> 位元移動運算子 5
< > <= >= 不等於關係運算子 6
== != 等於關係運算子 7
& ^ | 位元邏輯運算子 8,9,10
&& || 邏輯運算子 11,12
程式設計(二)
‐12‐
第三講:Java 檔案輸出入
輸入一個成績檔(score.txt),計算總和後輸出到另一個檔案(sum.txt)
Step 1: 程式參數(arguments)的使用
Step 2: 檔案輸入
Step 3: 檔案輸出
程式設計(二)
‐13‐
程式碼
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
import java.io.*;
public class Ex3Class {
public static void main(String[] args) {
// TODO Auto‐generated method stub
String filename1, filename2;
filename1 = args[0];
filename2 = args[1];
BufferedReader sr;
PrintWriter sw;
int s1, s2;
double average;
try
{
FileReader reader = new FileReader(filename1);
FileWriter writer = new FileWriter(filename2);
sr = new BufferedReader(reader);
sw = new PrintWriter(writer);
String line = sr.readLine();
while (line !=null && line.length() >0)
{
String[] scores = line.split(",");
s1 = Integer.parseInt(scores[0].trim());
s2 = Integer.parseInt(scores[1].trim());
average = ((double) s1 + s2) /2;
sw.printf("%3d %3d %7.3f\n", s1, s2, average);
line = sr.readLine();
}
sr.close();
sw.close();
}
catch (FileNotFoundException fe) {
System.out.println(fe.getMessage());
return;
}
catch (IOException ie) {
System.out.println(ie.getMessage());
return;
程式設計(二)
‐14‐
38
39
40
}
}
}
Note1: 使用 Java 程式參數
args[0]是第一個程式參數,args[1]是第二個程式參數
Note2: Java 例外處理機制
使用 IO 函數必須處理 IOException 例外。例外處理機制是 Java 提供給程式設計
人員捕捉程式中可能發生的錯誤所提供的機制。
Note3: 使用 BufferedReader 取得檔案輸入
BufferedReader 在建構時接受一個 Reader 物件。然後,使用 readline()讀入檔案
的一行。
Note4:使用 PrintWriter 輸出檔案
PrintWriter 在建構時接受一個 Writer 物件。然後,使用 printf()寫出資料到檔案。
Note5:字串的切割及除白
使用字串的切割函數 split(),將數字拆開。trim()函數去除多餘的空白。
Note6:字串轉整數
使用 Integer.parseInt()將字串轉換成整數。
程式設計(二)
‐15‐
第四講:Java 的亂數
從 1~49 的數字中選出 6 個不可重覆數字。
Step 1: 使用亂數物件
Step 2:產生常態分配的模擬資料
Step 3:產生 1~49 中不重覆的 6 個模擬數字
程式設計(二)
‐16‐
程式碼
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
import java.io.*;
import java.util.*;
public class Ex4Class {
static Random random = new Random();
public static void main(String[] args) {
int[] numbers = NumGen();
System.out.printf("random number is:");
for (int i=0; i< 6; i++)
System.out.printf(" %2d", numbers[i]);
}
static int[] NumGen()//1~49 不可重覆
{
int i, j;
int[] ball = new int[49];
int[] numList = new int[6];
int biggest, which=0;
for (i=0; i< 49; i++)
{
ball[i]=random.nextInt();
}
for (i=0; i<6; i++)
{
biggest = ‐1;
for (j=0; j <49; j++)
{
if (ball[j] > biggest)
{
biggest = ball[j];
which = j;
}
}
ball[which] = ‐1;
numList[i]= which + 1;
}
return numList;
}
}
程式設計(二)
‐17‐
Note1: 整數亂數的範圍
整數亂數的範圍: ‐ 2147483648~2147483641 (‐231~231‐1)
Note2: 高斯亂數的範圍
範圍 normal distribution with mean 0.0 and standard deviation 1.0.
Note3: 陣列的宣告及使用
int[] numList = new int[6]; 變數型別後面+ []就成了陣列變數。可以同時把參數傳給函
數或從函數輸出。
Note4: 靜態宣告
因為 main()函數是宣告靜態(static),所以其呼叫的類別或成員函數都必須加上靜態
(static) 宣告。
習題:
修改程式,產生一個有 10000 萬注樂透資料(49 取 6)的文字檔案。
程式設計(二)
‐18‐
第五講:樂透對獎
從檔案中讀出一萬筆樂透資料,計算每一注中獎的號碼數。
Step 1: 使用程式參數(arguments)決定輸入/輸出檔案名稱(參考第三講)
Step 2: 從檔案輸入一萬筆資料,並且進行數字陣列的轉換(參考第三講)
Step 3: 沒有排序的資料比對
程式設計(二)
‐19‐
Step 4: 有排序的資料比對
程式碼
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
import java.io.*; import java.util.*; public class Ex5Class { static Random random = new Random(); public static void main(String[] args) { String filename1, filename2; filename1 = args[0]; filename2 = args[1]; BufferedReader sr; PrintWriter sw; int[] bingo = NumGen(); int[] nn = new int[6]; try { FileReader reader = new FileReader(filename1); FileWriter writer = new FileWriter(filename2); sr = new BufferedReader(reader); sw = new PrintWriter(writer); System.out.printf("bingo number is:"); sw.printf("bingo number is:"); for (int i=0; i< 6; i++) { System.out.printf(" %2d", bingo[i]); sw.printf(" %2d", bingo[i]); } System.out.println(); sw.println(); Arrays.sort(bingo);
程式設計(二)
‐20‐
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
String line = sr.readLine(); while (line !=null && line.length() >0) { String[] numbers = line.split(","); for (int i=0; i<6; i++) { nn[i] = Integer.parseInt(numbers[i].trim()); } Arrays.sort(nn); int matchNum = NumMatchSorted(bingo, nn); System.out.printf("[%2d] %2d, …", matchNum, nn[0],…); sw.printf("[%2d] %2d, …", matchNum, nn[0], …); System.out.println(); sw.println(); line = sr.readLine(); } sr.close(); sw.close(); } catch (FileNotFoundException fe) { System.out.println(fe.getMessage()); return; } catch (IOException ie) { System.out.println(ie.getMessage()); return; } } static int NumMatchUnSorted(int[] refNum, int[] stakeNum) { int match = 0; for (int i = 0; i < 6; i++) { for (int j=0; j< 6; j++) { if (refNum[i]==stakeNum[j]) { match++;//中獎號碼數+1 } } } return match; } static int NumMatchSorted(int[] refNum, int[] stakeNum) { int match = 0; for (int i = 0, j = 0; i < 6 && j < 6;) {
程式設計(二)
‐21‐
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
120
121
122
123
124
125
126
127
128
129
if (refNum[i]==stakeNum[j]) { match++;//中獎號碼數+1 i++; j++; } else if(refNum[i]> stakeNum[j]) j++; else i++; } return match; } static int[] NumGen()//1~49 不可重覆 { int i, j; int[] ball = new int[49]; int[] numList = new int[6]; int biggest, which=0; for (i=0; i< 49; i++) { ball[i]=random.nextInt(); } for (i=0; i<6; i++) { biggest = -1; for (j=0; j <49; j++) { if (ball[j] > biggest) { biggest = ball[j]; which = j; } } ball[which] = -1; numList[i]= which + 1; } return numList; } }
程式設計(二)
‐22‐
第六講:JSP 程式
Step 1: 下載 Apache Tomcat http://tomcat.apache.org/
Step 2: 安裝 Apache Tomcat
Step 3:記得管理者帳號
程式設計(二)
‐24‐
Step 6:設定平台
Step 7: 開新 JSP 檔案(四次), ex‐vote.jsp, ex‐confirm.jsp, ex‐save.jsp, ex‐list.jsp
程式設計(二)
‐25‐
Step 7: 下載 MySQL Connector/J
http://dev.mysql.com/usingmysql/java/
Step 8: 下載 MySQL Connector/J
Step 9: MySQL Connector/J 加入到專案
程式設計(二)
‐28‐
程式碼 ex‐vote.jsp
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
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<!DOCTYPE html PUBLIC "‐//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http‐equiv='Content‐Language' content='zh‐tw'>
<meta http‐equiv='Content‐Type' content='text/html; charset=BIG5'>
<title>2012 畢業旅行投票資料(ex‐vote)</title>
</head>
<body>
<p>2012 畢業旅行投票</p>
<form method='post' action='ex‐confirm.jsp'>
<table border='1' width='100%' id='table1'>
<tr>
<td align=right width=200>學號</td>
<td><input type='text' name='SID' size='10'> </td>
</tr>
<tr>
<td align=right width=200>姓名</td>
<td><input type='text' name='SName' size='10'> </td>
</tr>
<tr>
<td align=right width=200>身份證末四碼</td>
<td><input type='text' name='SCode' size='10'></td>
</tr>
<tr>
<td align=right width=200>選擇地點</td>
<td><input type='radio' value='澎湖' name='SLoc'>澎湖
<input type='radio' value='花蓮' name='SLoc'>花蓮
<input type='radio' value='泰國' name='SLoc'>泰國</td>
</tr>
程式設計(二)
‐29‐
38
39
40
41
42
43
44
45
46
47
48
49
50
<tr>
<td align=right width=200>意見</td>
<td><input type='text' name='SComment' size='50'> </td>
</tr>
<tr>
<td align=right width=200> </td>
<td><input type='submit' name='Submit' value='投票'> </td>
</tr>
</table>
</form>
</body>
</html>
程式碼 ex‐confirm.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<html>
<head>
<meta http‐equiv='Content‐Language' content='zh‐tw'>
<meta http‐equiv='Content‐Type' content='text/html; charset=big5'>
<title>2012 畢業旅行投票資料(ex‐confirm)</title>
</head>
<%
//將表單元件的值轉成 jsp 變數
request.setCharacterEncoding("Big5");
String Var1 = request.getParameter("SID");
String Var2 = request.getParameter("SName");
String Var3 = request.getParameter("SCode");
String Var4 = request.getParameter("SLoc");
String Var5 = request.getParameter("SComment");
%>
<body>
<p>2010 生姿畢業旅行投票‐確認投票</p>
<form method='post' action='ex‐save.jsp'>
<table border='1' width='100%' id='table1'>
<tr>
<td align=right width=200>學號</td>
程式設計(二)
‐30‐
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
<td><input type='hidden' name='SID' value='<%= Var1 %>'><%= Var1
%></td>
</tr>
<tr>
<td align=right width=200>姓名</td>
<td><input type='hidden' name='SName' value='<%= Var2 %>'><%= Var2
%></td>
</tr>
<tr>
<td align=right width=200>身份證末四碼</td>
<td><input type='hidden' name='SCode' value='<%= Var3 %>'><%= Var3
%></td>
</tr>
<tr>
<td align=right width=200>選擇地點</td>
<td><input type='hidden' name='SLoc' value='<%= Var4 %>'><%= Var4
%></td>
</tr>
<tr>
<td align=right width=200>意見</td>
<td><input type='hidden' name='SComment' value='<%= Var5 %>'><%=
Var5 %></td>
</tr>
<tr>
<td align=right width=200>
<input type='submit' name='Submit' value='確認投票'></td>
<td>
<%
if (Var4=="")
out.print( "沒有選擇地點<a href='javascript:history.back()'>,請回上一頁重新填
寫</a>");
else
out.print( "若要更改<a href='javascript:history.back()'>,請回上一頁重新填寫
</a>");
%>
</td>
</tr>
</table>
程式設計(二)
‐31‐
62
63
64
65
<hr>
</form>
</body>
</html>
程式碼 ex‐save.jsp
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
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "‐//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http‐equiv='Content‐Language' content='zh‐tw'>
<meta http‐equiv='Content‐Type' content='text/html; charset=big5'>
<title>2012 畢業旅行投票資料(ex‐save)</title>
</head>
<%
//將表單元件的值轉成 jsp 變數
request.setCharacterEncoding("Big5");
String Var1 = request.getParameter("SID");
String Var2 = request.getParameter("SName");
String Var3 = request.getParameter("SCode");
String Var4 = request.getParameter("SLoc");
String Var5 = request.getParameter("SComment");
%>
<%
//將表單元件的值存入資料庫
String SID = new String(Var1.getBytes("Big5"), "ISO‐8859‐1");
String SName = new String(Var2.getBytes("Big5"), "ISO‐8859‐1");
String SCode = new String(Var3.getBytes("Big5"), "ISO‐8859‐1");
String SLoc = new String(Var4.getBytes("Big5"), "ISO‐8859‐1");
String SComment = new String(Var5.getBytes("Big5"), "ISO‐8859‐1");
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://aiplab.net:3306/coursedb";
Connection con = DriverManager.getConnection( url,"db_user", "password");
Statement stmt = con.createStatement();
程式設計(二)
‐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
String query="INSERT INTO vote(SID, SName, SCode, SLoc, SComment)
VALUES('"+SID+"', '"+SName+"', '"+SCode+"', '"+SLoc+"', '"+SComment+"')";
stmt.executeUpdate(query);
con.close();
%>
<body>
<p>2010 生姿畢業旅行投票‐投票完成</p>
<table border='1' width='100%' id='table1'>
<tr>
<td align=right width=200>學號</td>
<td><%= Var1 %></td>
</tr>
<tr>
<td align=right width=200>姓名</td>
<td><%= Var2 %></td>
</tr>
<tr>
<td align=right width=200>身份證末四碼</td>
<td><%= Var3 %></td>
</tr>
<tr>
<td align=right width=200>選擇地點</td>
<td><%= Var4 %></td>
</tr>
<tr>
<td align=right width=200>意見</td>
<td><%= Var5 %></td>
</tr>
</table>
<hr>
<a href='ex‐list.jsp'>查看報名資料</a>
</body>
</html>
程式碼 ex‐list.jsp
1
2
3
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<%@ page import="java.sql.*" %>
程式設計(二)
‐33‐
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
<!DOCTYPE html PUBLIC "‐//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http‐equiv="Content‐Language" content="zh‐tw">
<meta http‐equiv="Content‐Type" content="text/html; charset=big5">
<title>2012 畢業旅行投票資料(ex‐list)</title>
</head>
<body>
<p>2012 畢業旅行投票資料</p>
<%
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://aiplab.net:3306/coursedb";
Connection con = DriverManager.getConnection( url,"db_user", "password");
Statement stmt = con.createStatement();
String query="SELECT SID, SName, SLoc, SComment, SDate FROM vote ORDER BY
SDate";
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
int num_rows=rs.getMetaData().getColumnCount();
%>
<p> <%= num_rows %> 筆投票資料</p>
<table border="1" width="100%" id="table1">
<tr>
<td>學號</td>
<td>姓名</td>
<td>選擇地點</td>
<td>投票時間</td>
<td>意見</td>
</tr>
<%
while (rs.next()) {
String SID = new String(rs.getString(1).getBytes("ISO‐8859‐1"), "Big5");
String SName = new String(rs.getString(2).getBytes("ISO‐8859‐1"), "Big5");
String SLoc = new String(rs.getString(3).getBytes("ISO‐8859‐1"), "Big5");
Timestamp SDate = rs.getTimestamp(5);
程式設計(二)
‐34‐
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
String SComment = new String(rs.getString(4).getBytes("ISO‐8859‐1"), "Big5");
%>
<tr>
<td><%=SID %></td>
<td><%=SName %></td>
<td><%=SLoc %></td>
<td><%=SDate %></td>
<td><%=SComment %>_</td>
</tr>
<%
}
%>
</table>
<hr>
投票結果
<table border="1" width="100%" id="table2">
<tr>
<%
rs.close();
query="SELECT Count(SLoc) AS SNum, SLoc FROM vote GROUP BY SLoc";
stmt.execute(query);
rs = stmt.getResultSet();
while (rs.next()) {
int SNum = rs.getInt(1);
String SLoc = new String(rs.getString(2).getBytes("ISO‐8859‐1"), "Big5");
%>
<td><%=SLoc %></td>
<td><%=SNum %></td>
<%
}
con.close();
%>
</tr>
</table>
</body>
</html>