<HTML>
 <head><meta http-equiv="Content-Type"
 content="text/html; charset=big5" /></head><font color=blue size=4><b>

<BODY bgcolor=#bbffee> <b><font size=4>

<pre>
LAB04  ~򰵤Wg + mߥ Java Application gXҵ{ <font color=DarKred>
     (iHHegL C/C++ ӧ, ۤvSgLhcopyOH C/C++ӧ]i!)</font><font color=red>
Due: Y_g</font>(CWL@gE)
Purpose: x C/C++ {אּ Java `Nƶ, ýƲߨҽsXWh
<font color=Red> Ъ`N: 
     nD  e3.nctu.edu.tw Qװ ̷ӳWw post ú
B <font color=Blue> Subject: LAB04 from ǸmW </font>
eO߱o + Running Script  + Line numbers{X</font>
LAB04_05_06_07 ҵ{Uؼgk<font color=red>
  *** D@]Aӥ|gmD: Lab04, Lab05, Lab06, Lab07 (٦ĤKD)</font>
  аѦҩҵd: <font color=darkBlue>
     http://www.cs.nctu.edu.tw/~tsaiwn/oop/03_Labs/Lab04/   idc.cpp M idcheck.c
       a. C++ gҵ{ (uΨ C++ @Ǩǥ\)<font color=red>> idc.cpp </font>
       b. º C gҵ{ <font color=red>idcheck.c</font>  (iLX id Ҧ~)
</font>
   * ѦҤWǴPҦD:
     <a href="http://www.cs.nctu.edu.tw/~tsaiwn/introcs/story/idcheck.htm" target=_blank> http://www.cs.nctu.edu.tw/~tsaiwn/introcs/story/idcheck.htm </a>
     ΦۦW䨭ҽsX, FѦpP_@ӨҸXOXk?

   * JӬsҵd(C/C++dһPJavad), UˬdPp⪺ statements

   * dҤrഫƦrOĥ table look up (dk)
     s{X, ҦHno˰?
      Yo˰? ٦Ǥ|gkҿk?

   * C++ dҵ{ idc.cpp u|LX@ؿ~.. ҭYn@ӿJ ID LX
     Ҧi઺~nק?  (QXNCd idcheck.c)
<font color=darkRed>
(1)LAB04  ~򧹦Wg + mߥ Java Application gXҵ{
   (A)Ʋ: sդeD MyFirstCoffee.java (PqP)
      n@Applet ]n@ Application, I(click) Applet eݬ
      M[J@ǥylϱo@ ApplicationɥiHkW X {
     Hint: nΨ WindowListener  windowClosing; Ѧҧڵd:
       http://www.cs.nctu.edu.tw/~tsaiwn/oop/  ̭lؿ java
       <a href="http://www.cs.nctu.edu.tw/~tsaiwn/oop/java/03_sample_JavaPrograms/01_gigi/" target=_blank> java/03_sample_JavaPrograms/01_gigi/ </a>  ̭U GiGi*.java
   (B)mߥ Java Application gXҵ{ <font color=red>
      gXS  GUI Yi, NO rNn 
  oD²:)  idcheck.c ӤjXNiHn :-) (nns@U!) </font>
  ĳD{u new ۤv, uˬdu@gbO functionp testID():
  ]A class O class IDCheck { //...  D{: <font color=darkRed>
        IDCheck me = new IDCheck( );
        me.testID( );
     }// main(   // oO Java  main !
     void testID( ) { // C  int main( ); <font color=red>W٥i int main()  </font>
        //...
     } // testID(  </font>
  Y٬Oӷ|, ѦҥؿUHlؿ sample_BATNUM ̭ C P Java
  רOs C ]٤ӷ|nJӬݸ̭Ud stepwise refinementL{!
  M]n bat6ok.c P bat6ok.java nnӤ@U! </font> <font color=red>
HUwiӦUgm: </font>
(2)LAB05  LAB04  Java אּ GUI ( Frame, Button, TextField)
   ib class Τ@ Frame Φۤv extends java.awt.Frame
<font color=darkBlue>
(3)LAB06  LAB05  Java אּ Applet, üg@² HTML PtX
   `Ng Java {MiH@ Java Application
</font><font color=darkGreen>
(4)LAB07 mߥκ(HTML) + <font color=red>JavaScript </font>gXҵ{
   `N JavaScript O Java, oӴNu@ HTML 
   hݤ@Ǻ˵ ==> lX Niݨ@ JavaScript 
   {unݴXӺN|,  JavaScript , oݬݴN: 
http://residence.educities.edu.tw/brencar/JsTeach/JsTeach_grammar.html
   γo̦ykPо:  http://www.w3schools.com/jS/
   AMۤv gogle.com d JavaScript о
</font> <font color=darkRed>
(5)LAB08 ҵ{(Javag²{) 
     LAB04  Java application 令(ΧAgӧ),
     tXڵ TCP Server dҵy@ק, ft, NܦF!</font>
<font color=Red>
(6)Extra credit:
   mߥκ(HTML) + CGI { gXҵ{,
   YJ ID e Server ݥ CGI {P_ҸXO_Xk
   A⵲Gκe^ Browser. <font color=blue>
   `Nҿ CGI {O|b Server ݰyg{!
   i google.com  "FORM P CGI" </font>
     * A CGI {iH C  PERL Ψ䥦Awy 
     * ]i PHP  䥦p ASP, JSP   <font color=darkRed>
   `No ID ˬdu@Ob Server , Ob client ݪ Browser  </font>
Ѧ: http://webdesign.about.com/od/cgi/ss/aa022299.htm
      http://www.ck.tp.edu.tw/~thyu/perl-cgi-faq/pcp_faq.html
     Φۤv gogle.com  "FORM CGI о"  峹
</pre>
You are the
<!-- Start of SimpleHitCounter Code -->
<!--
<a href="http://www.simplehitcounter.com" target="_blank">
------>
<img src="http://simplehitcounter.com/hit.asp?uid=726858&f=255&b=65535" border="0" height="24" width="83" alt="Counter">

<!--
<br><a href="http://www.simplehitcounter.com" target="_blank">
<font size="-3">free hit counters</font>
--->
<!-- End of SimpleHitCounter Code -->
visitors to this page.

</pre>
<hr color=red size=3>

</pre>

<!--------  28  on  Tue Mar 16 08:17:30 CST 2010
----------------------------------------------->
<hr size=3 color=red>
<br>
<b><font color=red size=5> idc.cpp</font><font color=blue>
(ĳ{٤Oܼilؿsample_BATNUMݬ gbatnum{L{)</font>
<font color=blue size=4>
<pre>

     1	//idc.cpp -- @CopyLeft by tsaiwn@csie.nctu.edu.tw
     2	//g++ idc.cpp
     3	#include &lt;iostream>
     4	using namespace std;
     5	#include &lt;ctype.h>
     6	int checkID(char *p);
     7	main()    /*** Last upDate: Mon, 1 Feb 1999 ***/
     8	{ 
     9	  char what[][70]={ "!!oOXkҦr", //T0
    10	                    "..Ĥ@ӦrOr",   //T1
    11	                    "AOĤTʶ?",              //T2
    12	                    "ӵuF! X!!",         //T3
    13	                    "|ohX!!",         //T4
    14	                    "!!ӬOƦr!!",     //T5
    15	                    "ƦrXӬO"};      //T6
    16	  cout &lt;&lt; "*********************************" &lt;&lt; endl;
    17	  cout &lt;&lt; "*********ҵ{**********" &lt;&lt; endl;
    18	  cout &lt;&lt; "*********************************" &lt;&lt; endl;
    19	  char id[16];
    20	  while(38==38){
    21	        cout &lt;&lt; "пJҸX : ";
    22	        cin.getline(id, sizeof(id));   // getline ڤ| NewLine!
    23	        if (cin.fail()) {
    24	                if (cin.eof())  {    //EOF encounted?
    25	                        cout &lt;&lt; endl;   // print NewLine
    26	                        break;   // leave the while Loop
    27	                }// if EOF
    28	                cin.clear();  // clear Error Status
    29	                cin.ignore(0xffff, '\n'); //drop till '\n',̦h65535 chars
    30	                cout &lt;&lt; "JrӪI\n";
    31	                continue;  // go back to while
    32	        }// if cin.fail
    33	        // got an ID in char id[ ] , starting check the ID
    34	        if (id[1] == 'U' || id[1] == 'u') break;  // qUit ?
    35	        if (id[0] == '.' &amp;&amp; id[1] == 0) {   // first char is dot(.)
    36	                break;
    37	        }
    38	        cout &lt;&lt; "*********J '.' ***********" &lt;&lt; endl;            
    39	        cout &lt;&lt; "====>" &lt;&lt; what[checkID(id)] &lt;&lt; endl ;
    40	  }   //XT
    41	  cout &lt;&lt; "***********bye! bye!************" &lt;&lt; endl;
    42	  return 0;   // main should return 0 to indicate there is no error
    43	}  // main(
    44	int checkID(char *p) {
    45	     char y[26]={ 10,11,12,13,14,15,16,17, 34,  //ABCDEFGH I
    46	                  18,19,20,21,22, 35,           //JKLMN O
    47	                  23,24,25,26,27,28,            //PQRSTU
    48	                  29,32,30,31, 33 };            //VWXYZ 
    49	     int sum = 0;       //sumOFp⨭ҬO_Tܼ
    50	     if  (isalpha(p[0])) {
    51	         char ktmp= toupper( p[0] ); // see "man isalpha", nΨ &lt;ctype.h> 
    52	         ktmp= y[ ktmp - 'A' ];      // ର table y[] ƭ, s^ ktmp
    53	         sum += (ktmp / 10) + 9* ( ktmp % 10 ); // `N int/int o
    54	          // sum  ktmp/10 Ƴ[W9HktmpH10l
    55	     } else {
    56	         return 1;   //YĤ@Xp[0]Ҥ^.ܿJ~;Ǧ^~X 1
    57	     }//if..else..
    58	     if (p[1] != '1' &amp;&amp; p[1] != '2')  return 2; 
    59	     //ҲĤGXʧOX: 1k.2k, YOhǦ^~X2
    60	        int j;  //UӪ9XҸXMOƦr
    61	                // NѤUXOH8.7.6.5.4.3.2.1
    62	        for (j = 1;j &lt; 9; j++) {
    63	            if (p[j] == 0) return 3;   //X{ NULL, XǦ^~X5
    64	            if (isdigit(p[j]))  sum += (p[j]-'0') * (9-j) ; 
    65	            else  return 5;   // found non_digit
    66	        }//for
    67	        if(!isdigit(p[9])) return 5; // OѤF̫@X]OƦr
    68	        sum += p[9]-'0';   // ̫@X(ˬdX) 񭫤]O 1
    69	        if (p[10] != 0) return 4; // 11XNULL_hǦ^~X 4=Ӫ
    70	        if ( (sum %10) != 0) return 6;    //Y[vMO0, Ǧ^~X6 
    71	        return 0;
    72	 }// checkID(

</pre>
<hr size=3 color=red>
<b><font color=red size=5> idcheck.c</font><font color=blue>
(ĳ{٤Oܼilؿsample_BATNUMݬ gbatnum{L{)</font>
<font color=blue size=4>
<pre>

     1	//idcheck.c -- by tsaiwn@csie.nctu.edu.tw
     2	//gcc idcheck.c
     3	//gӵ{iHˬdҸXO_T
     4	//Extra credit: J 999 hͤ@ӥiΪXkҸX
     5	////////////
     6	#include &lt;stdio.h>
     7	#include &lt;ctype.h>
     8	void generateID( ), squeeze(char*); // ŧi function 
     9	int testID(char*);  // d稭ҦUإi઺~ öǦ^~NX
    10	void printError(int code); // print error message according code
    11	
    12	// `N Java ݭnŧi, ]b class SY 
    13	
    14	int main( ) {
    15	   static char id[99];  // 'a :-) Ҥ~ 10 X 
    16	   int code = 0;   // ΨӰO~NX 
    17	   while(38 == 38) {   // for( ;; ) {
    18	       printf("пJҸX Input ID: ");
    19	       fgets(id, sizeof(id), stdin); // CŪJ  id
    20	       // check EOF 
    21	       if(feof(stdin)) break;  //EOF == ^D in Unix; ^Z on DOS/Window
    22	       squeeze(id); // Ҧťճh  white space
    23	       //printf("strlen(id)=%d\n", strlen(id));
    24	       if(strcmp(id, "-1") == 0) break; //Java  id.equals("-1")
    25	       if(strcmp(id, ".") == 0) break; 
    26	       if(strcmp(id, "quit") == 0) break; 
    27	       if(id[1] == 'U') break;  // QUIT ?  // Java  id.charAt(1)==
    28	       if(strcmp(id, "999") == 0) {generateID( ); continue; }
    29	       code = testID(id);  // o~N, 0 ܵL :-)
    30	       printf(" ID %s is ", id);
    31	       if(code==0) printf(" OK.\n");   // LXoXT 
    32	       else {
    33	          printf(" Error ID! Reason(s):\n");
    34	       }//if
    35	       printError(code); // ̾ code LT 
    36	   }// while(
    37	   printf("\r\nThank you and bye bye!\n");
    38	   return 0;
    39	}//main(
    40	
    41	//  squeeze(char*) onΪ function, ] C {wS,ۤvg:
    42	//`N NewLine ] white space, ҥHoƤ]|ڪ '\n' !
    43	// ] fgets ŪJƧڦ NewLine; C++  getline hS NewLine!
    44	void squeeze(char*p) {    // Ҧ white space; Java np󰵩O?
    45	   char*p2 = p;    
    46	   if(*p == 0)return;   // NULL terminated, @}lNr굲: Ŧr
    47	   while(*p2 !=0) {  // white space Ь  K&amp;RҥĤGP B
    48	      if(isspace(*p2)) { ++p2; continue; }  // ᱼ white space
    49	      *p = *p2; 
    50	      p++; ++p2;   // advance one char
    51	   }//while
    52	   *p = *p2;  // 0 == '\0'   == NULL 
    53	}// squeeze(
    54	
    55	//  int testID(char* id) : ̾ڨҳWhd id Ǧ^~NX
    56	int yy[ ]={ 10,11,12,13,14,15,16,17, 34,  //ABCDEFGH I
    57	            18,19,20,21,22,  35,   //JKLMN O
    58	            23,24,25,26,27,28,     //PQRSTU
    59	            29,32,30,31, 33 };     //VWXY Z 
    60	int checkSum(char * id){  //  checkSum  testID(id)  
    61	   int sum, i;    // ]sXSӦr, κ⪺nܦh if(...
    62	   int ynum;
    63	   // άdk table look up dXrƸ²檽ı !
    64	   // حӪ int yy[ ] = { 10, 11, 12, 13, ...};  // ӳWw AB..
    65	   // M Let i = id[0]rh 'A' o 0..25
    66	   // AdX yy[i] ӥ: ynum = yy[i];  // 10..OO35..ZO35 !!
    67	   i = id[0] - 'A';
    68	   ynum = yy[i];
    69	   sum = ynum/10 + 9* (ynum%10);  // weight 1, 9, [876543211]
    70	   for(i=1; i&lt;=8; ++i) sum += (id[i] - '0') *(9-i);  // 87654321
    71	   sum += (id[9] - '0') ;  // *1   ˬdX weight ]O  1
    72	   return sum;   // ڥutdX checksum
    73	}//checkSum(
    74	
    75	int testID(char* id) {   //Ǧ^~NX, i bitwise "&amp;" BX 
    76	   int i, ans = 0, sum=0;  // sum ΨӺ weighted check sum
    77	   id[0] = toupper(id[0]); // ରjg
    78	   if(!isalpha(id[0])) ans = ans + 1;  // 1   ans = ans | 1;
    79	   if(id[1] != '1'  &amp;&amp; id[1] != '2') ans += 2; // 2  kͤk?
    80	   if(strlen(id) &lt; 10) ans += 4;   // ӵu
    81	   if(strlen(id) > 10) ans += 8;   // Ӫ
    82	   for(i=1; i&lt;=9; ++i) if(!isdigit(id[i])) ans = ans | 16; // DƦr
    83	   if((ans&amp;16) != 0) return ans;  // DƦrΦA check sum  
    84	   if(ans != 0) return ans;  // N..NΦA check sum  
    85	   sum = checkSum(id);   // ]SLǦrNX check sum
    86	   if(sum%10 != 0) ans |= 32;   // H 10 oɤ~ 
    87	   return ans;
    88	}// testID(
    89	
    90	char what[ ][88]={ "!!oOXkҦr", //T0
    91	                "..Ĥ@ӦrOr!",    // T1
    92	                "AOĤTʶ?",            // T2
    93	              "ӵuF!X!!",      // T3
    94	              "|ohX!!",     // T4
    95	            "!!ӬOƦr!!",   // T5     
    96	            "ƦrXӬO??"     // T6
    97	                };  // do NOT forget the ";"
    98	// String what[ ] = { ... };  // in Java 
    99	void printError(int code) {  // print all errors found use bitwise and
   100	   int i, yy[ ] = {0, 1, 2, 4, 8, 16, 32, 64, 128};
   101	   if(code == 0) { printf("%s\n", what[0]); return; }
   102	   for(i=1; i &lt;= 6; ++i)if((code&amp;yy[i]) != 0)printf("%s\n", what[i]);
   103	}// printError(
   104	
   105	void generateID( ) {
   106	   char id[11]={ 0 };   // | 0  (NULL)  ==  '\0'   == 0
   107	   int i;
   108	   id[0] = 'A' +  rand( ) % 26;  // 'A' .. 'Z'
   109	   id[1] = '1' + rand( ) % 2;   // '1' .. '2'
   110	   for(i=2; i&lt;=8; ++i) {
   111	     // ζüƥͥX id[2] .. id[8]
   112	     id[i] = '0' + rand( )%10;   // '0' .. '9'
   113	   } //
   114	   /// id[9] OˬdX, n, i '0' s checkSum( )Aվ 
   115	   id[9] = '0';
   116	   i = checkSum(id);   // ɥ i Ӧs  checkSum
   117	   i = i % 10;
   118	   if(i != 0) id[9] = '0' + (10-i);     // ˬdX 
   119	   printf(" Good ID: %s\n", id);   // legal ID now
   120	}// generateID(

</pre>
<hr size=3 color=red>
<b><font color=red size=5> bat6ok.c</font><font color=blue>
(ĳ{٤Oܼilؿsample_BATNUMݬ gbatnum{L{)</font>
<font color=blue size=4>
<pre>
   1 //bat6ok.c  -- @CopyLeft by tsaiwn@csie.nctu.edu.tw
   2 //BATtle of NUMbers
   3 //modified by __Ǹ__  _m_W_  and  __Ǹ__  _m_W_ 
   4 ///
   5 // Y Java h class ]_; classWٶPɮצW٬ۦP !
   6 // B main  public static void main(String xxx[ ]) {
   7 #define repeat  do {
   8 #define until(x)   } while(! (x) )
   9 
  10 #include &lt;stdio.h>
  11 #include &lt;stdlib.h>
  12 #include &lt;time.h>
  13 
  14 #define MAX_STONE 31
  15 #define MIN_STONE 18
  16 #define MAX_TAKE 9
  17 //Java HWγo public final static int MAX_TAKE = 9;
  18 
  19 #ifndef __cplusplus
  20   typedef enum {false=0, true } bool; // C { o
  21 #endif
  22 
  23 // define some global variables for the Game
  24 int nStone; // number of Stone
  25 int maxTake; // max stone to take for some game
  26 
  27 bool lastToWin;  // Win or Lose if took last one stone?
  28 bool userFirst, playAgain;
  29 /// 
  30 enum player {USER, COMPUTER};  // o˼g᭱iHUSER/COMPUTER
  31 enum player who; // who is taking the stone? ?
  32   // Java  enum Ьݥɮ׳̫᪺ɥR ! 
  33 void hello( ), prepareGame( ), playGame( );
  34 bool askUserFirst( ), askPlayAgain( );
  35 void userTurn( ), computerTurn( );
  36 void randomize( ) { srand(time(0));  } // ɶӷ@üƺؤl
  37 
  38 int main( ) {
  39    hello( ); 
  40    randomize( );  // randomize; make it true random
  41    repeat
  42       prepareGame( );
  43       userFirst = askUserFirst( );
  44       playGame( );
  45       playAgain = askPlayAgain( );
  46    until( ! playAgain );
  47    printf("Thank you for your play.\r\n");
  48    return 0;
  49 }
  50 
  51 void hello( ) {  
  52    printf("Welcome to the BATNUM game ...\r\n");
  53 }
  54 
  55 void prepareGame( ) {
  56    char msg[ ][88]={"Lose the game.", "win the game."};
  57    nStone = MIN_STONE + rand( ) % (MAX_STONE-MIN_STONE+1);
  58    maxTake = 3 + rand( ) % (MAX_TAKE -3 +1);  // 3..
  59    lastToWin = rand( )%2 == 1;  // half chance @b|
  60    printf("\r\nThere are %d stones.\r\n", nStone);
  61    printf("At least take 1, at most %d stones.\r\n", maxTake);
  62    printf("The one who take the last stone will ");
  63    printf("%s\r\n", msg[lastToWin]); // ̫@ӿ٬OĹ?
  64 #ifdef DEBUG
  65    printf("lastToWin=%d\n", lastToWin);
  66 #endif
  67 } // prepareGame
  68 
  69 bool askUserFirst( ) {
  70    static char buf[99];
  71    fprintf(stderr, "Do you want to go first(Y, N)? ");
  72    fgets(buf, sizeof(buf), stdin);
  73    if(buf[0]=='N' || buf[0]=='n') return false; //no
  74    if(buf[0]==0) return false;  // no!  C{ true/false
  75    return true;  //  Yes otherwise
  76 }
  77 
  78 bool askPlayAgain( ) {
  79    static char buf[99];
  80    fprintf(stderr, " Play again(Y, N)? ");
  81    fgets(buf, sizeof(buf), stdin);
  82    if(buf[0]=='N' || buf[0]=='n') return false; //no
  83    if(feof(stdin)) return false;  // EOF encounted
  84    return true;  // Yes
  85 } // askPlayAgain
  86 
  87 void playGame( ) {
  88    bool userWin=true; // assume user win
  89    if(userFirst) userTurn( );
  90    else printf(" OK. I go first.\r\n");
  91    while(nStone > 0 ) {
  92       computerTurn( );
  93       if(nStone &lt;= 0) break; // gameOver
  94       userTurn( );
  95    } // game Over when leave the while Loop
  96    userWin = true; // assume you win
  97    if(lastToWin &amp;&amp; (who == COMPUTER) ) userWin = false; // user !
  98    if( (!lastToWin) &amp;&amp; (who == USER) ) userWin = false; // user ]O
  99    if(userWin) printf(" Congratulations! You win!\r\n");
 100    else printf(" Sorry, I won! Ha ha!\n");
 101 } // playGame
 102 
 103 void userTurn( ) { 
 104    int nTake, canTake;
 105    static char buf[99];
 106    who = USER;  // now USER 's turn  O USER
 107    canTake = maxTake;  // ӳWw̦huள maxTake
 108    if(nStone &lt; maxTake) canTake = nStone;  // ShF
 109    printf(" How many you want to take(1..%d)? ", canTake);
 110    fgets(buf, sizeof(buf), stdin);
 111    nTake = (int)atol(buf);  
 112    // check if the nTake is legal ?
 113    // .. YųWwhnD USER sJ
 114    // .. ]igYJtƪ give up, N game :-(
 115    while(nTake &lt; 1 || nTake > canTake) { // illegal
 116       printf("  ?? Error, please re-type(1..%d)? ", canTake);
 117       fgets(buf, sizeof(buf), stdin);
 118       nTake = (int)atol(buf);  
 119    }
 120    nStone -= nTake;
 121    if(nStone == 0) printf(" You just took the last stone.\r\n");
 122    else printf(" %d stone(s) left.\r\n", nStone);
 123    return;
 124 } // userTurn
 125 
 126 void computerTurn( ) {
 127    int nTake = 1;
 128    who = COMPUTER;  // now is COMPUTER 's turn O COMPUTER
 129    // Ĺ?  Ҽ{̫@Ĺ٬O
 130    nTake = nStone;
 131    if(!lastToWin) nTake--;  // ̫@ӬO飮, d@ӵ
 132    nTake = nTake % (1+maxTake);
 133    if(nTake == 0) nTake = 1; // q|, ֮@ӵ⮳:-)
 134    if(nTake > nStone) nTake = nStone; // Sh! (io)
 135   ///
 136    nStone -= nTake;  // 
 137    printf(" I take %d stone", nTake);
 138    if(nTake > 1) printf("s");  // Ƽ
 139    printf(" this time.");
 140    if(nStone == 0) printf(" I just took the last stone.\r\n");
 141    else printf(" Now %d stone(s) left.\r\n", nStone);
 142 } // computerTurn
 143 ///   === === END of the program BATNUM === ===
 144 /***  Java  enum: b C/C++  enum O, i Java O!
 145   Java  enum O|ܦ class ! нsĶݬݥؿhX class !
 146   HUO²d, isĶåB:
 147   //gg.java  -- test enum in Java, by tsaiwn@csie.nctu.edu.tw
 148   //avac gg.java
 149   //java gg
 150   //javap gg$player
 151   class gg {
 152        enum player {USER, COMPUTER}; 
 153     public static void main(String xx[ ]) {
 154        player yy = player.USER;
 155        System.out.println("user="+yy);
 156        if(yy == player.USER) System.out.println("YES yy is player.USER");
 157        else System.out.println("NO hahaha!");
 158     }//main
 159   } // class gg
 160 *************************************************************/

</pre>
<hr size=3 color=red>
<b><font color=red size=5> bat6ok.java</font><font color=blue>
(ĳ{٤Oܼilؿsample_BATNUMݬ gbatnum{L{)</font>
<font color=blue size=4>
<pre>

     1	//bat6ok.java -- modified from bat6ok.c
     2	//javac bat6ok.java
     3	//java bat6ok
     4	///////////////////////////////////////////////////
     5	//bat6ok.c  -- @CopyLeft by tsaiwn@csie.nctu.edu.tw
     6	//BATtle of NUMbers
     7	//modified by __Ǹ__  _m_W_  and  __Ǹ__  _m_W_ 
     8	///
     9	// Y Java h class ]_; classWٶPɮצW٬ۦP !
    10	// B main  public static void main(String xxx[ ]) {
    11	import java.io.*;
    12	import java.util.*;
    13	
    14	class bat6ok {   //  filename should be the same as class name
    15	
    16	 public final static int MAX_STONE = 31;
    17	 public final static int MIN_STONE = 18;
    18	 public final static int MAX_TAKE = 9;
    19	
    20	 // define some global variables for the Game
    21	  int nStone; // number of Stone
    22	  int maxTake; // max stone to take for some game
    23	
    24	  boolean lastToWin;  // Win or Lose if took last one stone?
    25	  boolean userFirst, playAgain;
    26	  /// 
    27	enum player {USER, COMPUTER};  // o˼g᭱iHUSER/COMPUTER
    28	 player who;  // who is taking the stone? ? `N Java gk !
    29	
    30	public static void main(String xxx[  ]) {
    31	    bat6ok ggyy = new bat6ok( );
    32	    ggyy.main( );
    33	}
    34	bat6ok( ) {   // constructor
    35	     prepareIO( );
    36	}
    37	BufferedReader cin=null;
    38	PrintStream cout=null;
    39	
    40	void prepareIO( ) {
    41	     try {
    42	        cin =  new BufferedReader(
    43	                     new InputStreamReader( System.in )  );
    44	        cout = System.out;
    45	     }catch(Exception e) {  }
    46	}
    47	
    48	int main( ) { // Ӫ main( ); Note that it has different prototype
    49	   hello( ); 
    50	   randomize( );  // randomize; make it true random
    51	   do {
    52	      prepareGame( );
    53	      userFirst = askUserFirst( );
    54	      playGame( );
    55	      playAgain = askPlayAgain( );
    56	   } while( playAgain );
    57	   cout.printf("Thank you for your play.\r\n");
    58	   return 0;
    59	}
    60	
    61	int rand( ) {
    62	     return (int) (32767* Math.random( ) );
    63	}
    64	void srand(int seed) {
    65	} // not necessary :-)
    66	void randomize( ) {
    67	     srand((int)System.currentTimeMillis( ) );
    68	}
    69	
    70	void hello( ) {  
    71	   cout.printf("Welcome to the BATNUM game ...\r\n");
    72	}
    73	
    74	void prepareGame( ) {
    75	   String msg[ ]={"Lose the game.", "win the game."};
    76	   nStone = MIN_STONE + rand( ) % (MAX_STONE-MIN_STONE+1);
    77	   maxTake = 3 + rand( ) % (MAX_TAKE -3 +1);  // 3..
    78	   lastToWin = rand( )%2 == 1;  // half chance @b|
    79	   cout.printf("\r\nThere are %d stones.\r\n", nStone);
    80	   cout.printf("At least take 1, at most %d stones.\r\n", maxTake);
    81	   cout.printf("The one who take the last stone will ");
    82	   int kkk;   kkk = 0;
    83	   if(lastToWin) kkk = 1;
    84	   cout.printf("%s\r\n", msg[kkk]); // ̫@ӿ٬OĹ?
    85	} // prepareGame
    86	
    87	boolean askUserFirst( ) {
    88	    cout.printf( "Do you want to go first(Y, N)? ");
    89	    String buf = null;
    90	    try {
    91	          buf = cin.readLine( );
    92	    } catch(Exception e) { }
    93	    if(buf == null) return false;
    94	    if(buf.length( )==0) buf = "n";
    95	    if(buf.charAt(0)=='N' || buf.charAt(0)=='n') return false; //no
    96	    if(buf.charAt(0)==0) return false;  // no! 
    97	    return true;  //  Yes otherwise
    98	}
    99	
   100	boolean askPlayAgain( ) {
   101	    cout.printf( "Do you want to go first(Y, N)? ");
   102	    String buf = null;
   103	    try {
   104	          buf = cin.readLine( );
   105	    } catch(Exception e) { }
   106	    if(buf == null) return false;
   107	    if(buf.length( )==0) buf = "n";
   108	    if(buf.charAt(0)=='N' || buf.charAt(0)=='n') return false; //no
   109	    if(buf.charAt(0)==0) return false;  // no! 
   110	    return true;  // Yes
   111	} // askPlayAgain
   112	
   113	void playGame( ) {
   114	   boolean userWin=true; // assume user win
   115	   if(userFirst) userTurn( );
   116	   else cout.printf(" OK. I go first.\r\n");
   117	   while(nStone > 0 ) {
   118	        computerTurn( );
   119	        if(nStone &lt;= 0) break; // gameOver
   120	        userTurn( );
   121	   } // game Over when leave the while Loop
   122	   userWin = true; // assume you win
   123	   if(lastToWin &amp;&amp; (who == player.COMPUTER) ) userWin = false; // user !
   124	   if( (!lastToWin) &amp;&amp; (who == player.USER) ) userWin = false; // user ]O
   125	   if(userWin) cout.printf(" Congratulations! You win!\r\n");
   126	   else cout.printf(" Sorry, I won! Ha ha!\n");
   127	} // playGame
   128	
   129	void userTurn( ) { 
   130	   int nTake, canTake;
   131	   String buf;
   132	   who = player.USER;  // now USER 's turn  O USER
   133	   canTake = maxTake;  // ӳWw̦huள maxTake
   134	   if(nStone &lt; maxTake) canTake = nStone;  // ShF
   135	   cout.printf(" How many you want to take(1..%d)? ", canTake);
   136	   try {
   137	        buf = cin.readLine( );
   138	        if(buf==null) buf="0";
   139	        nTake = Integer.parseInt(buf);
   140	   }catch(Exception e) { nTake = 0;  }
   141	   while(nTake &lt; 1 || nTake > canTake) { // illegal
   142	      cout.printf("  ?? Error, please re-type(1..%d)? ", canTake);
   143	      try {
   144	           buf = cin.readLine( );
   145	           if(buf==null) buf="0";
   146	           if(buf.length( )==0) buf = "0";
   147	           nTake = Integer.parseInt(buf);
   148	      }catch(Exception e) {  nTake = 0; }
   149	   }
   150	   nStone -= nTake;
   151	   if(nStone == 0) cout.printf(" You just took the last stone.\r\n");
   152	   else cout.printf(" %d stone(s) left.\r\n", nStone);
   153	   return;
   154	} // userTurn
   155	
   156	void computerTurn( ) {
   157	   int nTake = 1;
   158	   who = player.COMPUTER;  // now is COMPUTER 's turn O COMPUTER
   159	   // Ĺ?  Ҽ{̫@Ĺ٬O
   160	   nTake = nStone;
   161	   if(!lastToWin) nTake--;  // ̫@ӬO飮, d@ӵ
   162	   nTake = nTake % (1+maxTake);
   163	   if(nTake == 0) nTake = 1; // q|, ֮@ӵ⮳:-)
   164	   if(nTake > nStone) nTake = nStone; // Sh! (io)
   165	  ///
   166	   nStone -= nTake;  // 
   167	   cout.printf(" I take %d stone", nTake);
   168	   if(nTake > 1) cout.printf("s");  // Ƽ
   169	   cout.printf(" this time.");
   170	   if(nStone == 0) cout.printf(" I just took the last stone.\r\n");
   171	   else cout.printf(" Now %d stone(s) left.\r\n", nStone);
   172	} // computerTurn
   173	
   174	} // class bat6ok
   175	///   === === END of the program BATNUM === ===

</pre>
<font color=blue size=4>
<a href="./LAB04.jar">
oDY LAB04.jar
 </a>
 &nbsp; &nbsp; &nbsp;

<a href="hint_C_to_Java.htm">
More hints to translate C programs into Java programs
</a>

<br/>
<br>
 &nbsp; BATNUM YC C 
<a href="bat6ok.c">
 bat6ok.c  l
</a>
 &nbsp;
 &nbsp; Java
<a href="bat6ok.java">
 bat6ok.java 
</a>
<br>
 &nbsp; &nbsp; &nbsp;
AѦ BATNUM Java s²k:
<a href="bat7.java">
bat7.java 
</a>
 &nbsp;<font color=red>
+ </font>
 &nbsp;
<a href="c2java.java">
c2java.java 
</a>

 &nbsp; &nbsp; &nbsp;

<br><br>
<a href="./sample_BATNUM"  
target=_blank>
  Nݬ./sample_BATNUM/ lؿ qs}lg batnum Y C
</a><br>
(iJlؿksɧ^Aq)
</pre>

<br>
 &nbsp; &nbsp; &nbsp;
 PERL g CGI 
<a href="../Lab05/for_Extra_credit/PerlCGI_FAQ.html"
  target=_blank>

 FAQ(`ݰD)
 ./for_Extra_credit/ 
</a>

<!------------
------------------>

</pre>
<hr size=2>
<font color=blue size=5>
<a href="./">
^oӧ@~ؿ(LAB04)
</a>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<a href="../">
^@~ؿ
</a>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<a href="../../">
^ҵ{ؿ
</a><br>

</pre>
You are the
<img src="http://simplehitcounter.com/hit.asp?uid=726858&f=255&b=65535" border="0" height="24" width="83" alt="Counter">
visitors to this page.
