要抓各範例只要 按右鍵存檔即可
若發現用 notepad 看時不會換列, 則用 more 處理一下就可:
more < oldFile > newFile
註: 那是因為有些檔案為 Unix 格式,
只有 NewLine(LF; LineFeed) 沒有 RETURN (CR)
Hint to translate a C/C++ program into a Java program
如何把 C 程式改為 Java Application?
很簡單:
(1) 最前面補上這些:
import java.io.*;
import ... 看有用到啥...
class ggyy { // 名稱要與檔案名伊樣
(2) 最後面補上這個, 這樣整個 C 程式被 class 包起來
} // class ends here
(3) 在 class 裡面寫這些: (前後不重要, 習慣上放前面)
BufferedReader cin = null;
PrintStream cout = null;
public static void main(String xxx[ ]) {
ggyy me = new ggyy( ); // ggyy 是你的 class name
me.prepareIO( );
me.main( ); // call 原先 C/C++ 的 main( )
}
ggyy( ) { } // 目前沒有事情做
void prepareIO( ) {
try{
cin = new BufferedReader(new InputStreamReader(System.in));
}catch(Exception e) {;} // Exception handling
cout = System.out;
} // that's OK now
void printf(String fmt, Object... yy) { // 必要時宣告為 static
cout.printf(fmt, yy);
}
(4) 若有寫 #include .. 通通殺掉
因為 Java 不認帳!
(5) 若有寫 #define xx yy
或是 const int xx=yy;
都改用 public static final int xx=yy;
例如 #define MAX_STONE 31
要改成:
public static finat int MAX_STONE = 31;
(6) 關於指標,
(a)若不是文字的指標就改成 array;
(b)若是文字的指標阿就是字串就改為 String,
這時要善用 String 的 .charAt(?)
例如 C 的 char *id; 或是 char id[99];
常會搭配使用 if(id[k] == ...) ...
這 if(id[k] == ...)... 就改為 if(id.charAt(k) == ...) ...
若要改變 id[k] 內容則不可用 String, 要改用 StringBuffer
StringBuffer s = "haha how are you?";
s.setCharAt(1, 'e'); s.setCharAt(3, 'e'); // ==> "hehe how are you?"
System.out.println("s=" +s);
** 注意 String s 的 內容不能改: s.charAt(2) = 'x'; // 錯錯錯
StringBuffer ss 才能改: ss.setCharAt(2, 'x');
(7) 關於亂數
C/C++ 的 inr rand( ) 在 Java 要用 Math.random()且不一樣
阿就是 0 <= Math.random( ) < 1 是 double 實數
那就寫一支int rand() 就可:
int rand( ) {
return (int) (32767* Math.random( ) );
} // 這樣是 0..32766
或這樣
int rand( ) {
return (int) ( Integer.MAX_VALUE * Math.random( ) );
} // 這樣是 0..MAX_VALUE -1
// 注意 Java 的 int 是 32-bit, 等於 C/C++ 的 long int;
// Java 的 long 是 64-bit, Java 整數都是 sign integer
// 還有 Java Math.random( ) 是自動換 SEED
// 注意 C 的 rand( ) 若不手動換 SEED 則每次重新執行都相同
(8) 程式中的 squeeze( ) 要怎辦?
Java 的 String 有 replace 函數, Try this:
String aa = " haha hehe how are you ";
String bb = aa.replace(" ", "");
bb = bb.replace("\t", "");
System.out.println("bb="+bb);
這樣大概就可以了! 包括你所有 printf 都 OK 了!
剩下是輸入以及字串處理...
** Java 要讀一整列要這樣(C 的 gets 或 fgets):
String s = null;
try {
s = cin.readLine( );
}catch(Exception e) {;}
** Java 要讀一個 char 要這樣:
int c = 0;
try {
c = cin.read( );
}catch(Exception e) {;}
if(c == -1 ) // EOF encounted 檔案結束!
** Java 要讀一整列上只有一個整數:
String stmp=null;
int ans=0;
try {
stmp = cin.readLine( );
ans = Integer.parseInt(stmp); // Double.parseDouble(stmp);
}catch(Exception e) {;}
// ans is what you want
** 若程式內有用到 scanf 那就比較麻煩 :-(
此時可以用 java.util.Scanner 一個一個讀入
或是改為用 readLine() 讀入整列後用 StringTokenizer 處理
** 如何使用 java.util.Scanner?
java.util.Scanner gg = new java.util.Scanner(System.in);
int n;
double x;
String haha;
if(gg.hasNextInt( )) n = gg.nextInt( );
if(gg.hasNextDouble( ) ) x = gg.nextDouble( );
if(gg.hasNext( )) haha = gg.next( );
可寫 while Loop 抓到 hasNext( ) 不成立為止 !
** Java 的字串處理更簡單
Java 的 String 是物件 (與 C++ class string 一樣 )
C 的 int strcmp(char*, char*) ?
String s = "abcd235 78ha ha ";
if(s.equals("hehehe") //... 字串是否相等 ?
if(s.startsWith("haha")) //...
s.substring(2,5) 是 "cd2" 表示 2-th 到 4-th (5-1 = 4)
s.replace(' ', ''); // 去掉所有的空白
s.charAt(3) 是 'd' 因為從第0字算起
if(s.charA(0) == 'q' ) // 開始是 q
if(s.equalsIgnoreCase("quit")) // 大小寫不管是否等於 "quit"
Please see javap java.lang.String
或用 Browser 看 java.sun.com 的 Java API References
| |
參考資料:
(a) java.sun.com 找 Java SE 1.6 (6.0) 的 API
連到 java.sun.com
(b) www.cplusplus.com C++參考好站
(c) http://gcc.gnu.org/onlinedocs/libstdc++/manual/spine.html
(d) http://www.csie.nctu.edu.tw/~tsaiwn/oop/02_handouts/
(e) http://www.csie.nctu.edu.tw/~tsaiwn/oop/java/03_sample_JavaPrograms/
不懂就舉手找助教來聊天 !
不懂就舉手找助教來聊天 !
不懂就舉手找助教來聊天 !
Cons.java
1 //cons.java --- Simple I/O example, @CopyLeft by tsaiwn@cs.nctu.edu.tw
2 import java.io.*;
3 import static java.lang.System.*; // so that can use in, out, err
4 class cons {
5 cons( ) { prepareIO( ); } // constructor
6 public static void main(String [ ]args) {
7 cons me = new cons( );
8 me.test( );
9 err.print("Wait 3 seconds ..");
10 try{
11 Thread.sleep(3123); // 3.123 seconds
12 }catch(Exception e) {;}
13 System.err.println(" OK...");
14 me.test2( );
15 test3( );
16 Console.WriteLine("Bye bye!"); // simulate CSharp C#
17 System.err.println("再見..再見! 再見!");
18 }
19 void test( ) {
20 System.err.print("Test ... ...");
21 err.println("Haha .. leaving Test ..."); // 也可, 因已有 import static
22 }//test(
23 void test2( ) {
24 Console.print(" Into Test2..");
25 Console.Write("... still Test2 ..");
26 print("... 還在 Test2..");
27 printf("... 仍是 Test2.."); print("\n"); // newLine
28 println("leaving test2...");
29 }// test2(
30 static void test3( ) { println("Test3..3 ..3 ..."); }//test3(注意 static
31 void prepareIO( ) {
32 cin = new BufferedReader(new InputStreamReader(System.in));
33 }
34 static void print(String s, Object... gg) {
35 out.printf(s, gg); // out 就是 System.out 因為有 import static
36 }
37 static void printf(String s, Object... gg) { print(s, gg); }
38 static void println(String s, Object... gg) {
39 Console.Write(s+"\n", gg);
40 }
41 static java.io.BufferedReader cin = null; // simulate C++
42 }// class cons
43 class Console { // simulate MicroSoft C# (CSharp) :-)
44 static String ReadLine( ) {
45 String s=null;
46 try{ s= cin.readLine( ); }catch(Exception e){;}
47 return s;
48 }
49 static void WriteLine(String s) { cout.println(s); }
50 static void Write(String fmt, Object... args) {
51 cout.printf(fmt, args);
52 }
53 static void print(String s) { Write(s);} // 這 line 可不寫
54 static void print(String s, Object... gg) { Write(s, gg); }
55 static void println(String s) {
56 WriteLine(s);
57 }
58 static void printf(String s, Object... gg) { Write(s, gg);}
59 static BufferedReader cin=null;
60 static {cin=new BufferedReader(new InputStreamReader(System.in));}
61 static java.io.PrintStream cout = System.out;
62 }//Console
63 /*************** =============================================
64 D:\JTest>javac cons.java
65 D:\JTest>java cons
66 Test ... ...Haha .. leaving Test ...
67 Wait 3 seconds .. OK...
68 Into Test2..... still Test2 ..... 還在 Test2..... 仍是 Test2..
69 leaving test2...
70 Test3..3 ..3 ...
71 Bye bye!
72 再見..再見! 再見!
73 D:\JTest> ****************************/
|
Jw.java
1 //Jw.java -- Java Window, @CopyLeft by tsaiwn@csie.nctu.edu.tw
2 //Demo simple GUI programming : GUI Layout + Event Driven
3 // GUI programming 類似在做勞作 :-)
4 import java.awt.*;
5 import java.awt.event.*;
6 import java.io.*; import java.util.*;
7 class Jw implements ActionListener{
8 Frame win = new Frame("Windows 2010");
9 Jw( ) { test( ); } // constructor
10 public static void main(String[ ] argv){ new Jw( ); }//main(
11 void test( ) {
12 printf("Give me your name: "); name = getline( );
13 printf("Give me an integer number: "); int num = getInt( );
14 win.setSize(300,300); win.setVisible(true);
15 Button bt = new Button(""+ new Date());
16 Panel p = new Panel( ); win.add("South", p);
17 win.add("North", bt); b6.setBackground(Color.white);
18 Panel p2 = new Panel( ); win.add("Center", p2);
19 p2.add(new Button(""+num+" "+name));
20 p2.add(b6); b6.setForeground(Color.red);
21 decorate(p); b6.setFont(new Font("細明體", 38, 38));
22 TT timer = new TT(bt); timer.start( ); // bt display date+time
23 Virus chang3 = new Virus( ); win.addWindowListener(chang3);
24 win.setVisible(true);
25 }//test(
26 static BufferedReader cin;
27 static PrintStream cout=System.out;
28 static{ cin = new BufferedReader(
29 new InputStreamReader( System.in ) );
30 }// do only once when the class is loaded into JVM memory
31 int getInt( ) {
32 String buf = "00";
33 try{ buf= getline( ); return Integer.parseInt(buf); }
34 catch(Exception e) { return 0; }
35 }// getInt
36 String getline( ) {
37 try{ return cin.readLine( ); }catch(Exception e){ return null;}
38 }//getline( ) similar to getline( ) in C++ I/O stream Library
39 void printf(String fmt, Object... gg){cout.printf(fmt, gg);}
40 int kk=100; String name;
41 Button b2, b3, b5, b6= new Button("" + kk);
42 static class Virus extends WindowAdapter{ // used as Listener
43 public void windowClosing(WindowEvent e){ // 按窗右上角 X 會到這
44 Frame w = new Frame("Ha haha");
45 int y = (int)(88*Math.random());
46 w.setSize(258+ y, 168); w.setLocation(398+y/38, y);
47 w.setVisible(true);
48 }//windowCl...
49 }// class Virus // used as Listener
50 void decorate(Panel p) {
51 b2 = new Button(" B2 "); b2.setBackground(Color.green);
52 b3 = new Button("PressMe"); b3.setBackground(Color.pink);
53 b5 = new Button("DogBark");
54 p.add(b2); p.add(b3); p.add(b5);
55 b3.addActionListener(this); b5.addActionListener(this);
56 }//decorate(
57 Color rgb[ ]={Color.red, Color.green, Color.blue};
58 static int cnow = 0;
59 public void actionPerformed(ActionEvent e){
60 if(e.getSource( ) == b5) System.exit(0);
61 b6.setLabel(""+ ++kk); b6.setForeground(rgb[cnow]);
62 if(kk%3==0) cnow++; cnow = cnow % rgb.length;
63 win.validate();
64 }//actionP...
65 static class TT extends Thread{ Button b=null;
66 TT(Button b){ this.b = b;}
67 public void run( ) { int gg=0;
68 while(true){ b.setLabel(""+new Date( ));
69 try{Thread.sleep(568);}catch(Exception e){;}
70 if(++gg %18 <= 8) b.setForeground(Color.red);
71 else b.setForeground(Color.black);
72 }//while
73 }//run(
74 }// class TT
75 }// class Jw
|
Jw2.java
1 //Jw2.java -- Java Window, @CopyLeft by tsaiwn@csie.nctu.edu.tw
2 //Demo simple GUI programming : GUI Layout + Event Driven 事件驅動
3 //This prgram has the same function as Jw.java
4 //But in this version, Jw2 is a Frame itself !
5 // GUI programming 類似在做勞作 :-)
6 import java.awt.*;
7 import java.awt.event.*; // 注意 這 package 不屬於 java.awt
8 import java.io.*; import java.util.*;
9 class Jw2 extends Frame implements ActionListener{
10 public static void main(String[ ] argv){ new Jw2( ).test(); }//main(
11 void printf(String fmt, Object... gg){cout.printf(fmt, gg);}
12 int kk=100; String name=null; // kk 值 會顯示在畫面中間
13 Button b2, b3, b5, b6= new Button("" + kk); // 弄些按鈕
14 /// 此處除 b6 外其他都還待 new 出實体, 目前只有 "reference"參考
15 PrintStream cout = System.out; // C++ cout, C: stdout, OS: 1
16 PrintStream cerr = System.err; // C++ cerr, C: stderr, OS: 2
17 BufferedReader cin = // C++ cin, C: stdin, OS: 0
18 new BufferedReader( new InputStreamReader( System.in ) );
19 void test( ) {
20 printf("Give me your name: "); name = getline( );
21 printf("Give me an integer number: "); int num = getInt( );
22 setSize(300,300); setVisible(true);
23 Button bTop = new Button(""+ new Date());
24 new TT(bTop).start( ); // bTop display date+time
25 Panel p = new Panel( ); add("South", p);
26 this.add("North", bTop); b6.setBackground(Color.white);
27 Panel p2 = new Panel( ); add("Center", p2);
28 p2.add(new Button(""+num+" "+name));
29 p2.add(b6); b6.setForeground(Color.red);
30 decorate(p); // 把伊些按鈕貼到 Panel p
31 b6.setFont(new Font("細明體", 38, 38)); // 字大一些
32 Virus chang3 = new Virus( ); addWindowListener(chang3);
33 setVisible(true); // 讓 user 看得見
34 b3.addActionListener(this); b5.addActionListener(this);
35 }//test( // add????Listener 是要求系統幫忙監看有沒有 event
36 void decorate(Panel p) {
37 b2 = new Button(" B2 "); b2.setBackground(Color.green);
38 b3 = new Button("PressMe"); b3.setBackground(Color.pink);
39 b5 = new Button("DogBark");
40 p.add(b2); p.add(b3); p.add(b5); // Add these Buttons to p
41 }//decorate( //Panal uses FlowLayout defaultly
42 int getInt( ) { // read an integer from Keyboard
43 try{ String buf= getline( ); return Integer.parseInt(buf); }
44 catch(Exception e) { return 0; } // 若亂打會回傳 0
45 }// getInt
46 String getline( ) { // read one Line from keyboard
47 try{ return cin.readLine( ); }catch(Exception e){ return null;}
48 }//getline( ) similar to getline( ) in C++ I/O stream Library
49 class Virus extends WindowAdapter{ // used as Listener
50 public void windowClosing(WindowEvent e){ // 按窗右上角 X 會到這
51 Frame w = new Frame("Ha haha");
52 int y = (int)(88*Math.random());
53 w.setSize(258+ y, 168); w.setLocation(398+y/38, y);
54 w.setVisible(true); // Ha ha ha 越關窗越多窗 !
55 }//windowCl...
56 }// class Virus // used as Listener
57 class TT extends Thread{ Button b=null;
58 TT(Button b){ this.b = b;} // 把參數抄到這 class 內
59 public void run( ) { int gg=0;
60 while(true){
61 b.setLabel(""+new Date( ));
62 try{Thread.sleep(568);}catch(Exception e){;}
63 if(++gg %18 <= 8) b.setForeground(Color.red);
64 else b.setForeground(Color.black);
65 }//while
66 }//run(
67 }// class TT
68 public void actionPerformed(ActionEvent e){ // call back function
69 if(e.getSource( ) == b5) System.exit(0);
70 b6.setLabel(""+ ++kk); b6.setForeground(rgb[cnow]);
71 if(kk%3==0) cnow++; cnow = cnow % rgb.length;
72 validate(); // refresh this window Frame
73 }//actionP...
74 int cnow = 0; // current color for Button b6
75 Color rgb[ ]={Color.red, Color.green, Color.blue};
76 }// class Jw2
|
foreach.java
1 //foreach.java -- @CopyLeft by tsaiwn@csie.nctu.edu.tw
2 //Demo how to use foreach, and how to use Arrays.sort
3 //For C++ STL user, see: http://www.cplusplus.com/reference/algorithm/
4 import static java.lang.System.out; // so that we can use out.print( )
5 class foreach {
6 static String names[ ]={"ABen", "Cat","Dog", "BBS", "GGYY", "cow","bull"};
7 public static void main(String[ ] args) {
8 int[] numbers = { 4, 5, 6, 49, 1, 2, 3, 38, -2, -1, 0 };
9 for (int k=0; k< numbers.length; ++k) { // normal usage (不是 foreach)
10 System.out.print(" "+ numbers[k]);
11 }// for
12 System.out.println( ); // newLine
13 java.util.Arrays.sort(numbers); // sort into ascending order
14 out.println("After sort..."); print(numbers);
15 out.println(".. sort into Reverse order(Descending) 遞減");
16 revGGYY(numbers); // Java 的 Comparator 不能用在 primitive type array
17 // 可是 Java 須用 Comparator 才能讓 Arrays.sort 遞減排序
18 // 若要用 Comparator 必須先用 wrapper 包起來, 例如 Integer( )
19 print(numbers); // 所以我們把 sort 好的顛倒過來就好 :-)
20 test2( ); // test sorting String Array; note that String is Object
21 out.print("Ha ha ha!\nBye bye...\n");
22 }//main(
23 static void revGGYY(int n[ ]) {
24 int t, len = n.length;
25 for(int i=0; i< len/2; ++i) { // OK
26 t = n[i]; n[i]= n[len-i-1]; n[len-i-1] = n[i];
27 }//for
28 }//revGGYY
29 static void print(int gg[ ]) {
30 for (int i : gg) Console.print(" "+ i); // foreach
31 Console.println( );
32 }
33 static void print(String gg[ ]) { // same name == function name overloading
34 for (String i : gg) Console.print(" "+ i); // foreach
35 Console.println( );
36 }
37 static void test2( ){
38 java.util.Comparator<String> arBen = new MyComparator( );
39 // 阿扁 arBen 有能力比較字串大小, 但會說相反話 :-)
40 out.println("\nNow doing test2, names are:"); print(names);
41 Console.println("=== After Sort names: 注意小寫比大寫字母還大");
42 java.util.Arrays.sort(names); // sort into ascending order
43 print(names);
44 Console.println("====== Sort names again use arBen ... 遞減");
45 java.util.Arrays.sort(names, arBen); // Descending order 遞減
46 print(names);
47 out.println("======== Sort with another Comparator.....不管大小寫");
48 java.util.Arrays.sort(names, new ABSorter( )); // 用無名氏做比較
49 print(names);
50 }//test2(
51 static java.io.PrintStream Console = System.out; // can use Console...
52 }//class
53 class MyComparator implements java.util.Comparator<String> { //比較器只用在物件
54 public int compare(String aa, String bb) {
55 if(aa.equals(bb)) return 0; // similar to use qsort in C Language
56 int ans = aa.compareTo(bb);
57 if(ans < 0) return 1; // Descending order 遞減排序
58 return -1;
59 }//compare(
60 }// a sorter class / blueprint
61 class ABSorter implements java.util.Comparator<String> { //比較器只能用在物件
62 public int compare(String aa, String bb) {
63 int ans = aa.compareToIgnoreCase(bb);
64 return ans; // Ascending order 遞增排序
65 //return -ans; // Descending 遞減! Why? Think about the return value
66 }//compare(
67 }// a sorter class / blueprint
68 /****** The following is extracted from a C# (CSharp) program:
69 int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
70 foreach (int i in numbers) {
71 System.Console.WriteLine(i);
72 }
73 Array.sort(numbers); System.Console.WriteLine("After sort..");
74 foreach (int i in numbers) System.Console.Write(i);
75 System.Console.WriteLine( );
76 ******************************************/
1 //arySort.cpp --- @copyLeft by tsaiwn@csie.nctu.edu.tw
2 //use C++ STL sort algorithm
3 //g++ arySort.cpp
4 //a.exe
5 #define DEBUG // comment out this line if you doNOT want debug msg
6 #include <algorithm>
7 #include <iostream>
8 using namespace std;
9 // /// primitive data array
10 int nums[ ] = {38, 23, 5, 8, 6, 123, 88, 55};
11 double xxx[ ] = {3.8, 2.3, 5, 8, 6, 12.3, 8.8, 5.5};
12 ///
13 bool comp(int a, int b) { // compare function for later use
14 return (b < a); // for 由大排到小 Descending order
15 // return (a < b); // for 由小排到大 Ascending
16 }
17 template<class T>
18 void print(T* x, int n){
19 for(int i=0; i<n; ++i) cout << x[i] <<" ";
20 printf("\n");
21 }
22 // a Comparator class:
23 template<class T>
24 class GGYY { public:
25 bool operator( ) (T i,T j) {
26 #ifdef DEBUG
27 cout << " S.";
28 #endif
29 return (j < i); // return i < j; // try this
30 }// operator()
31 }; // do NOT forget the ";" in C++
32 const int n = sizeof nums / sizeof nums[0];
33 const int nx = sizeof xxx / sizeof xxx[0];
34 void test2( ); // declare only
35 int main(int argc, char** argv) {
36 print(nums, n);
37 printf(" --- then sort using STL sort..\n");
38 sort(nums, nums+n); // STL, see http://www.cplusplus.com
39 print(nums, n);
40 ///
41 printf(" === sort with Comparator except 1st and last item:\n");
42 GGYY<int> arBen; // in Java: GGYY arBen = new GGYY( );
43 sort(nums+1, nums+n-1, arBen); // only sort middle part
44 //Note that Java Comparator 不可用於 primitive array
45 printf(" 注意 1st 和 last element 沒參與 sort :-)\n");
46 print(nums, n); // int nums[ ] 在 Java 是 primitive type array
47 printf(" ===============\n");
48 ///
49 printf(" === sort with my compare function:\n");
50 sort(nums, nums+n, comp); // compare function NOT allowed in Java
51 print(nums, n);
52 test2( );
53 }//main(
54 void test2( ){
55 printf("======Do test2\ntest2: "); print(xxx, nx);
56 GGYY<double> arBen; // in Java: GGYY arBen = new GGYY( );
57 sort(xxx, xxx+n); // Ascending
58 printf("test2: "); print(xxx, nx);
59 printf(" === sort with Comparator arBen:\n");
60 sort(xxx, xxx+n, arBen); // only sort middle part
61 printf("\ntest2: "); print(xxx, nx);
62 }//test2
63 /***** =======================================================
64 C:\testc>g++ arySort.cpp
65 C:\testc>a.exe
66 38 23 5 8 6 123 88 55
67 --- then sort using STL sort..
68 5 6 8 23 38 55 88 123
69 === sort with Comparator except 1st and last item:
70 S. S. S. S. S. 注意 1st 和 last element 沒參與 sort :-)
71 5 88 55 38 23 8 6 123
72 ===============
73 === sort with my compare function:
74 123 88 55 38 23 8 6 5
75 ===== ... ******** **********************/
76
|
回到作業目錄
回到課程目錄
You are the
-th visitors to this page.
|