一個(gè)人的Java

          2005年12月25日 #

          一個(gè)簡(jiǎn)單日記本的源程序,功能并不完全,請(qǐng)高人指點(diǎn)

          import java.awt.*;
          import java.awt.event.*;
          import javax.swing.*;
          import java.util.*;
          import java.text.*;
          import java.io.*;
          public class Note extends Frame {

          private MenuBar mb;
          private Menu mset_param ,mhelp;
          private MenuItem mibc ,miSound;
          private MenuItem miabout;
          //缺省的背景顏色
          private static Color backgroundcolor = Color.GRAY;

          //funtction of the button on plcb is chose year andmonth
          //and set alarm colock and remind booking
          private JCheckBox remindBook ,alarmColock;
          private JComboBox cbyears ,cbmonths;
          private JPanel plcb;
          //日歷按鈕
          private JPanel plbt;
          private JButton button[];
          //add vector to contain button[],so that find it
          private Vector v;
          //save the year and month
          private String choseyear ,chosemonth;
          private int choseyearint ,chosemonthint;
          private boolean changed = false;
          private boolean fileExist = false;//the application first run to find file
          private static boolean needSound;

          //add text to write down what to do in the future
          private TextArea tanote;
          private JPanel plta;

          //默認(rèn)的年份
          private final static String years[]={
          "1995" ,"1996" ,"1997" ,"1998" ,"1999" ,"2000" ,
          "2001" ,"2002" ,"2003" ,"2004" ,"2005" ,"2006" ,
          "2007" ,"2008" ,"2009" ,"2010" ,"2011" ,"2012" ,
          "2013" ,"2014" ,"2015" ,"2016" ,"2017" ,"2018" ,
          "2019" ,"2020"
          };

          private static final String months[] = {
          "January" ,"February" ,"March" ,"April" ,"May" ,"June" ,"July" ,"August" ,
          "September" ,"October" ,"November" ,"December"
          };

          private final static int dom[] = {
          31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31
          };

          //save the first day of the month to use
          private int start;
          //save the button who is entered
          private int btnIndex;

          public Note() {
          mb = new MenuBar();
          mset_param = new Menu("設(shè)置");
          mhelp = new Menu("幫助");
          mibc = new MenuItem("背景");
          miSound = new MenuItem("聲音");
          miabout = new MenuItem("關(guān)于...");

          mset_param.add(mibc);
          mset_param.addSeparator();
          mset_param.add(miSound);
          mhelp.add(miabout);
          setMenuBar(mb);
          mb.add(mset_param);
          mb.setHelpMenu(mhelp);

          MListener ml = new MListener();
          mibc.addActionListener(ml);
          miabout.addActionListener(ml);
          miSound.addActionListener(ml);

          cbyears = new JComboBox();
          cbmonths = new JComboBox();
          plcb = new JPanel();
          plcb.setLayout(new FlowLayout());
          JLabel lyears = new JLabel("年份:");
          JLabel lmonths = new JLabel("月份:");
          plcb.add(lyears);
          plcb.add(cbyears);
          plcb.add(lmonths);
          plcb.add(cbmonths);
          remindBook = new JCheckBox("預(yù)約提示",true);
          alarmColock = new JCheckBox("鬧鐘");
          // Dimension d = new Dimension();
          // remindBook.setSize(d);
          // remindBook.getSize(d);
          // System.out.println("W:"+d.getWidth()+" H:"+d.getHeight());
          plcb.add(remindBook);
          plcb.add(alarmColock);
          remindBook.addActionListener(new RemindListener());
          alarmColock.addActionListener(new RemindListener());
          add(plcb ,BorderLayout.NORTH);

          //add calendar
          getCalendar();

          plbt = new JPanel();
          plbt.setBackground(Color.BLUE);
          plbt.setLayout(new GridLayout(7 ,7));

          plbt.add(new JLabel(" 星期日"));
          plbt.add(new JLabel(" 星期一"));
          plbt.add(new JLabel(" 星期二"));
          plbt.add(new JLabel(" 星期三"));
          plbt.add(new JLabel(" 星期四"));
          plbt.add(new JLabel(" 星期五"));
          plbt.add(new JLabel(" 星期六"));

          //add calendar button to frame
          //add button to vector;
          v = new Vector();
          button = new JButton[42];
          for(int i=0;i<41;i++){
          button[i] = new JButton();
          plbt.add(button[i]);
          button[i].addActionListener(new ButtonListener());
          v.add(button[i]);
          }

          button[41] = new JButton();
          plbt.add(button[41]);
          button[41].setText("保存");
          button[41].addActionListener(new SaveListener());
          add(plbt ,BorderLayout.CENTER);

          //add note book
          // plta = new JPanel();
          tanote = new TextArea(5 ,80);
          // tanote.addTextListener(new tanoteTextListener());
          // tanote.setColumns(80);
          // plta.add(tanote);
          // tanote.SCROLLBARS_VERTICAL_ONLY;
          add(tanote ,BorderLayout.SOUTH);

          /*
          //add date to button
          GregorianCalendar calendar = new GregorianCalendar(choseyearint ,chosemonthint ,1);
          int start = calendar.get(Calendar.DAY_OF_WEEK)-1;
          int daysInMonth = dom[chosemonthint];
          if(calendar.isLeapYear(choseyearint)&&chosemonthint == 1){
          ++daysInMonth;
          }
          for(int i =0;i<daysInMonth;i++){
          button[start+i].setText(" "+(i+1)+" ");
          }
          */
          //add the default year and month to JComboBox
          for(int i= 0;i<=25;i++){
          cbyears.addItem(years[i]);
          }
          for(int i=0;i<12;i++){
          cbmonths.addItem(months[i]);
          }
          /*
          //add current year and month
          cbyears.setSelectedIndex(choseyearint-1995);
          cbmonths.setSelectedIndex(chosemonthint);
          */

          //show date to calendar
          showDate();
          //open file add to note
          Calendar now = new GregorianCalendar();
          int num = start + now.get(Calendar.DAY_OF_MONTH)-1;
          btnIndex = num;
          readFile(num);
          fileSound();

          //add threadcb to listen jcombobox state
          new ThreadCB().start();

          //listen the JComboBox of years and months
          cbyears.addItemListener(new cbyearsItemListener());
          cbmonths.addItemListener(new cbmonthsItemListener());

          addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
          dispose();
          System.exit(0);
          }
          });
          }

          /**
          *add menu listener to know the menu what do want to do
          */
          class MListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
          MenuItem i = (MenuItem)e.getSource();
          if(i.equals(miabout)){
          JOptionPane.showMessageDialog(null ,"日歷記事本程序V1.0","關(guān)于..." ,JOptionPane.INFORMATION_MESSAGE);
          }
          else if(i.equals(mibc)){
          //backgroundcolor = Color.BLACK;
          backgroundcolor = JColorChooser.showDialog(null ,"選擇顏色..." ,getBackground());
          setBackground(backgroundcolor);
          plbt.setBackground(backgroundcolor);
          // System.out.println(choseyear);
          ////
          }
          else{
          JOptionPane.showMessageDialog(null ,"I am sorry ,this function is not complation" ,"Sorry" ,JOptionPane.INFORMATION_MESSAGE);
          }
          }
          }

          /**
          *add the year JComboBox listener to know what active
          */
          class cbyearsItemListener implements ItemListener{
          public void itemStateChanged(ItemEvent e){
          // System.out.println(e.paramString());
          // System.out.println(e.getStateChange());
          // System.out.println(e.getItem().toString());
          // if(e.getSource().equals("1997")){
          // System.out.println("1997 is chosed");
          // }
          // else{
          // System.out.println("the System is not chose 1997");
          // }
          // choseyear = e.getItem().toString();
          changed = true;
          // showDate();
          // cbmonths.setSelectedIndex(5);
          }
          }

          /**
          *add the month JComboBox listener to know what active
          */
          class cbmonthsItemListener implements ItemListener{
          public void itemStateChanged(ItemEvent e){
          // System.out.println(choseyear);
          // chosemonth = e.getItem().toString();
          changed = true;

          // chosemonthint = Integer.parseInt(chosemonth);
          // System.out.println(chosemonthint);
          // showDate();
          }
          }

          public static void main(String args[]) {
          System.out.println("Starting Note...");
          Note mainFrame = new Note();
          mainFrame.setSize(600, 400);
          mainFrame.setTitle("日歷記事本");
          mainFrame.setBackground(backgroundcolor);
          mainFrame.setVisible(true);
          for(int i=0;i<10;i++){
          System.out.print("\007");
          }
          // Thread dd = new ThreadCB();
          // dd.start();
          // mainFrame.paintCalendar();
          }

          protected void getCalendar(){
          Calendar now = new GregorianCalendar();
          // System.out.println("year :"+now.get(Calendar.YEAR));
          // System.out.println("month:"+now.get(Calendar.MONTH));
          // int y = now.get(Calendar.YEAR);
          // choseyear = Integer.toString(y);
          // int m = now.get(Calendar.MONTH);
          // chosemonth = Integer.toString(m+1);
          choseyearint = now.get(Calendar.YEAR);
          chosemonthint = now.get(Calendar.MONTH);
          // System.out.println("y "+choseyear+"::"+chosemonth);
          }

          /**
          *show date to calendar
          */
          protected void showDate(){
          GregorianCalendar calendar = new GregorianCalendar(choseyearint ,chosemonthint ,1);
          start = calendar.get(Calendar.DAY_OF_WEEK)-1;
          int daysInMonth = dom[chosemonthint];
          if(calendar.isLeapYear(choseyearint)&&chosemonthint == 1){
          ++daysInMonth;
          }
          for(int i =0;i<daysInMonth;i++){
          button[start+i].setForeground(Color.BLACK);
          button[start+i].setText(" "+(i+1)+" ");
          }
          //set current day
          int nowDay = start + calendar.get(Calendar.DAY_OF_MONTH);
          button[nowDay+1].setForeground(Color.RED);
          //add current year and month
          cbyears.setSelectedIndex(choseyearint-1995);
          cbmonths.setSelectedIndex(chosemonthint);
          }

          //listen the buttons active
          class ButtonListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
          Object obj = e.getSource();
          // System.out.println("haha"+e.getSource());
          btnIndex = v.indexOf(obj);
          readFile(btnIndex);
          /* switch(v.indexOf(obj)){
          case 1:
          System.out.println("i am button1");
          break;
          case 2:
          // System.out.println("I am button2");
          readFile(2);
          break;
          case 41:
          System.out.println(tanote.getText());
          break;
          default:
          System.out.println("I do not know who am I");
          break;
          }
          */ }
          }

          /**
          *create a thread to listen the year or month′s state
          */
          class ThreadCB extends Thread{
          public void run(){
          while(true){
          if(changed){
          changed = false;
          choseyearint = cbyears.getSelectedIndex()+1995;
          chosemonthint = cbmonths.getSelectedIndex();
          //System.out.println("y:"+choseyearint+":M:"+chosemonthint);
          for(int i=0;i<40;i++){
          button[i].setText("");
          }
          showDate();
          }
          try{
          sleep(200);
          }
          catch(InterruptedException e){
          System.err.println(e);
          }
          }
          }
          }

          /**
          * add note book listener to know the textarea active
          */
          /*
          class tanoteTextListener implements TextListener{
          public void textValueChanged(TextEvent e){
          //System.out.println(e.getSource());
          }
          }*/

          /**
          *check file to know the file is exist
          * if exist,read it to the note book
          */
          protected void readFile(int bt){
          int y = cbyears.getSelectedIndex()+1995;//real year
          int m = cbmonths.getSelectedIndex()+1;//real month
          String fileName = Integer.toString(y) + Integer.toString(m)+"button"+Integer.toString(bt);
          // System.out.println("I am dudu");
          // System.out.println(fileName);
          // String fileName = "testDay.java";

          File file = new File(fileName);
          BufferedReader is;
          String line;
          StringBuffer sb = new StringBuffer();

          tanote.setText("");
          if(file.exists()){
          try{
          is = new BufferedReader(new FileReader(fileName));

          while((line = is.readLine())!= null){
          sb.append(line);
          sb.append("\n");
          }
          is.close();
          }
          catch(IOException e){
          System.err.println(e);
          System.exit(0);
          }
          tanote.setText(sb.toString());
          fileExist = true;
          }
          else{
          System.out.println(fileName+" is not exists");
          }

          }

          /**
          *sound
          */
          protected void fileSound(){
          if(remindBook.isSelected()){
          if(fileExist){
          /* for(int i=0;i<10;i++){
          System.out.println("\007");
          }
          */
          needSound = true;
          }
          }
          }

          /**
          *listen the save button active
          */
          class SaveListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
          int bt = btnIndex;
          int y = cbyears.getSelectedIndex()+1995;//real year
          int m = cbmonths.getSelectedIndex()+1;//real month
          String fileName = Integer.toString(y) + Integer.toString(m)+"button"+Integer.toString(bt);

          try{
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
          //int row = tanote.getRows();
          //System.out.println("rows:"+row);
          String s = tanote.getText();
          System.out.println("length:"+s.length());
          bw.write(s);

          bw.close();
          }
          catch(IOException ev){
          System.err.println(ev);
          System.exit(0);
          }
          }
          }

          //
          class RemindListener implements ActionListener{
          public void actionPerformed(ActionEvent ae){
          Object obj = ae.getSource();
          if(obj.equals(remindBook)){
          if(remindBook.isSelected()){
          System.out.println("I am selected");
          }
          else{
          System.out.println("I am not selected");
          }
          }
          else{
          if(alarmColock.isSelected()){
          // System.out.println("I am selected");
          final JFrame jf = new JFrame("設(shè)置時(shí)間");
          jf.setSize(300,100);
          jf.setLocation(200 ,200);
          jf.setVisible(true);
          // Font f = new Font( ,Font.BOLD ,20);
          JLabel jl = new JLabel("逗你玩");
          String name=jl.getFont().getName();
          // System.out.println("Font:"+name);//name′s value is Dialog
          Font f = new Font(name ,Font.BOLD+Font.ITALIC ,20);
          jl.setForeground(Color.red);
          jl.setFont(f);
          jf.getContentPane().setLayout(new GridLayout(5 ,2));
          jf.getContentPane().add(new JLabel(" "));
          jf.getContentPane().add(jl);
          jf.getContentPane().add(new JLabel("sorry! this function is not do!!"));
          jf.pack();
          jf.addWindowListener(new WindowAdapter(){
          public void windowClosing(WindowEvent we){
          jf.dispose();
          }
          });
          }
          else{
          System.out.println("I am not selected");
          }
          }
          }
          }
          }

          posted @ 2005-12-25 15:35 lemon 閱讀(1249) | 評(píng)論 (0)編輯 收藏

          2005年12月12日 #

          關(guān)于JAVA學(xué)習(xí)

               本人這段時(shí)間暫時(shí)沒(méi)有學(xué)習(xí)JAVA了,所以很少來(lái)上面發(fā)文章。但我個(gè)人覺(jué)得JAVA還是很有趣的語(yǔ)言,我以后還會(huì)繼續(xù)學(xué)習(xí)的,謝謝大家的支持…

          posted @ 2005-12-12 21:37 lemon 閱讀(243) | 評(píng)論 (0)編輯 收藏

          2005年12月2日 #

          本人博客中國(guó)的分欄代碼,分享一下

          <!--用iframe來(lái)裝入2005索引頁(yè),這樣我們就獲得了所有本年度的文章列表了-->
          <!--<iframe id="cataloghtml" src="catalog_2005.html" style=display:none;position:absolute;top:400;left:400;z-index:250

          ></iframe>-->
          <script>
          var startYear = 2005; //你的博客是哪一年建立的?
          var showCount = 10; // 每個(gè)欄目顯示多少條?


          var d = new Date();
          var currYear = d.getUTCFullYear();
          for(i=currYear;i>=startYear;i--)
          {
          document.writeln('<iframe id="cataloghtml'+i+'" src="catalog_'+i+'.html"

          style=display:none;position:absolute;top:400;left:400;z-index:250 ></iframe>');
          }
          </script>
          <script>
          //這部分的腳本是自動(dòng)更新用的
          //從cataloghtml的categoryname這個(gè)欄目讀取文章列表放到當(dāng)前頁(yè)面的mycategoryname中
          function showcatalog(mycategoryname,categoryname)
          {
          var currShowCount = 0;
          var currTotalCount = 0;
          l="<ul type='circle'>";
          for(iyear=currYear;iyear>=startYear;iyear--)
          {
          currCategory = document.body.all[mycategoryname];
          ol = eval("cataloghtml"+iyear+".document.body.all");

          var entityDiv = null;
          for(i=0;i<ol.length;i++)
          {
          if(ol[i].className =="entity")
          {
          entityDiv = ol[i];break;
          }
          }
          ol = entityDiv.children.tags("UL");
          var oLI=null;
          for(i=0;i<ol.length;i++)
          {
          if(ol[i].children(0).name==categoryname)
          {
          oLI = ol[i].children.tags("LI");
          break;
          }
          }
          if(oLI == null) return ;
          for(i=0;i<oLI.length;i++)
          {
          if(i>showCount-1) break;
          oA = oLI[i].children(1);
          s = oA.innerHTML;
          pos = s.search(/[)|】|』|\]]{1}/);
          if(pos>0)s=s.slice(pos+1);
          l += "<li style='width:245px;height:18;overflow:hidden'><a href='"+oA.href+"' target='_blank'>"+s+"</a></li>\r\n";
          }
          currShowCount += i;
          currTotalCount += oLI.length;
          }

          for(;currShowCount<showCount;currShowCount++)
          l += "<li style='width:245px;height:18;overflow:hidden'>...</li>\r\n";

          l+="</ul>";
          currCategory.insertAdjacentHTML("beforeend",l);
          // 增加代碼,統(tǒng)計(jì)欄目文章數(shù)
          titleDIV = currCategory.parentElement.children(0);
          titleDIV.insertAdjacentHTML("beforeend","("+ currTotalCount +")");
          }


          //從cataloghtml讀取目錄并生成當(dāng)前頁(yè)面

            function showallcatalog()

            {

            //需要改寫(xiě)的地方之一

            showcatalog("mcategory1","category1");//※情感綠洲

            showcatalog("mcategory2","category2");//※文學(xué)草坪

            showcatalog("mcategory3","category3");//※科教園地

            showcatalog("mcategory4","category4");//※電腦網(wǎng)絡(luò)
           
                  showcatalog("mcategory5","category5");//※院校文化

            showcatalog("mcategory6","category6");//※都市生活

            showcatalog("mcategory7","category7");//※影音娛樂(lè)

            showcatalog("mcategory8","category8");//※人在北京

            //……

            //注意,上面的省略號(hào)表示如果還有第九、第十個(gè)標(biāo)題欄時(shí)依此類(lèi)推,寫(xiě)類(lèi)似的代碼

            }

            </script>

          <!--當(dāng)body裝入后調(diào)用showallcatalog()裝載最新文章列表-->

            <body onload=showallcatalog()>

            

              <div><div class="mydiv1" target="_blank"><div class="mybg_01" target="_blank"><a href="

              <div><div class="mydiv2" target="_blank"><div class="mybg_01" target="_blank"><a href="

              <div><div class="mydiv1" target="_blank"><div class="mybg_01" target="_blank"><a href="

              <div><div class="mydiv2" target="_blank"><div class="mybg_01" target="_blank"><a href="

              <div><div class="mydiv1" target="_blank"><div class="mybg_01" target="_blank"><a href="

             <div><div class="mydiv2" target="_blank"><div class="mybg_01" target="_blank"><a href="

             <div><div class="mydiv1" target="_blank"><div class="mybg_01" target="_blank"><a href=" class="myimg" alt="查看更多影音娛樂(lè)的文章,請(qǐng)點(diǎn)擊此處" src="

             <div><div class="mydiv2" target="_blank"><div class="mybg_01" target="_blank"><a href="

             </div></p>

          posted @ 2005-12-02 19:38 lemon 閱讀(593) | 評(píng)論 (0)編輯 收藏

          2005年10月18日 #

          好的Java風(fēng)格

          為什么代碼很重要
          盡管JAVA是用來(lái)寫(xiě)程序而不是散文, 但它仍然被用來(lái)表達(dá)思想和觀(guān)點(diǎn)的。而且,在調(diào)查中顯示,那些思想和觀(guān)點(diǎn)在實(shí)際中完成了很多事情。為編寫(xiě)出好的JAVA風(fēng)格而擔(dān)憂(yōu),似乎是在浪費(fèi)時(shí)間, 但實(shí)際上它對(duì)我們編寫(xiě)程序是很適宜的,因?yàn)樗磉_(dá)的思想和觀(guān)點(diǎn)是格外清晰的。

          這里提供一些理由,為什么要使用好的JAVA代碼規(guī)范


          一個(gè)軟件產(chǎn)品的80%的生命期是在維護(hù)(maintenance)。
          幾乎沒(méi)有一個(gè)軟件在它的整個(gè)生命期里都是被它的作者來(lái)維護(hù)的。
          使用好的風(fēng)格提高了軟件的可維護(hù)性。  
          如果源代碼和軟件產(chǎn)品是捆綁給客戶(hù)的,作為產(chǎn)品的剩余部分,它應(yīng)該有好的分包(well-packaged),足夠清晰和專(zhuān)業(yè)的代碼。

          使用好的風(fēng)格編寫(xiě)代碼有以下幾點(diǎn)好處:


          提高了代碼的可讀性,持續(xù)性,和諧性。這些都能使代碼能更容易的理解和維護(hù)。
          使代碼更容易被跟蹤和調(diào)試,因?yàn)樗乔逦暮统掷m(xù)的。
          使你或另一個(gè)程序員在編寫(xiě)終止時(shí)更容易再繼續(xù)下去,尤其在一個(gè)很長(zhǎng)的時(shí)間后。
          增加了代碼預(yù)排(walkthroughs)的好處, 因?yàn)槟茏寘⑷胝吒嗟膶⒔裹c(diǎn)集中在代碼正在做什么。

          概要方針
          使用好的JAVA風(fēng)格并不困難, 但是它確實(shí)需要注意細(xì)節(jié)。下面是一些常用的概要指導(dǎo)方針:


          使代碼更清晰和更容易讀  
          使代碼更持續(xù)  
          使用顯而易見(jiàn)的標(biāo)識(shí)符名  
          邏輯地組織你的文件和類(lèi)  
          每個(gè)文件只有一個(gè)類(lèi)(這里不包括一些內(nèi)部類(lèi))
          使用80-90個(gè)字符的最大行寬  
          明智的使用空格來(lái)and/or其他分隔符
          縮排上,使用空格(Space)來(lái)代替Tab

          Tabs vs. 空格
          在編寫(xiě)代碼時(shí),“Tabs vs. 空格” 是一個(gè)嚴(yán)謹(jǐn)?shù)挠^(guān)點(diǎn)。這里我并不是暗示只有一個(gè)正確的方法。我支持使用空格,因?yàn)樗鼙WC我的代碼在你的編輯器里和我的編輯器里看到的相同,反之矣然。如果你感覺(jué)使用空格來(lái)代替Tab"不是正確的", 那么就使用Tab吧。

          括號(hào)和縮進(jìn)
          在編寫(xiě)代碼時(shí),縮進(jìn)風(fēng)格(cf., Raymond, "Indent Style"),或者放置括號(hào)("{" 和 "}") 和一些相關(guān)聯(lián)的縮進(jìn)代碼,是另一個(gè)嚴(yán)謹(jǐn)?shù)挠^(guān)點(diǎn)。象JAVA一樣,有許多C風(fēng)格的語(yǔ)言存在。我這里也不是暗示它們中哪一個(gè)更優(yōu)先更好。在大多數(shù)本文的范例代碼中,我使用了K&R 風(fēng)格,如果你不喜歡K&R風(fēng)格,那么就使用其他風(fēng)格吧。

          注釋
          在JAVA代碼中你可以使用兩種注釋?zhuān)?Javadoc 注釋 (也稱(chēng)為文檔注釋) 和執(zhí)行注釋。 Javadoc注釋能夠被javadoc工具解壓來(lái)制造一個(gè)API文檔。執(zhí)行注釋是那些解釋代碼目的和方式的注釋。在注釋你的JAVA代碼時(shí)請(qǐng)使用以下方針:


          盡可能的使用Javadoc注釋(在類(lèi)和方法上,使之能最小化).
          多使用塊注釋?zhuān)偈褂?/注釋, 除非一些特殊的情況,如變量聲明
          要記?。汉米⑨屖怯袔椭模瑝淖⑨屖锹闊┑?。

          Example 1. Bad Comment Style

          // applyRotAscii() -- Apply ASCII ROT
             private void applyRotAscii(){
                try{
                   int rotLength = Integer.parseInt(rotationLengthField.getText().trim()); // get rot len
                   RotAscii cipher = new RotAscii(rotLength); // new cipher
                   textArea.setText(cipher.transform(textArea.getText())); // transform
                }catch(Exception ex){
                   /* Show exception */
                   ExceptionDialog.show(this, "Invalid rotation length: ", ex); }
             }



          Example 2. Good Comment Style

          /**
              * Apply the ASCII rotation cipher to the user's text. The length is retrieved
              * from the rotation length field, and the user's text is retrieved from the
              * text area.
              *
              * @author Thornton Rose
              */
             private void applyRotAscii() {
                int      rotLength = 0;  // rotation length
                RotAscii cipher = null;  // ASCII rotation cipher
            
                try {
                   // Get rotation length field and convert to integer.
                    
                   rotLength = Integer.parseInt(rotationLengthField.getText().trim());
                  
                   // Create ASCII rotation cipher and transform the user's text with it.
                    
                   cipher = new RotAscii(rotLength);
                   textArea.setText(cipher.transform(textArea.getText()));
            
                 } catch(Exception ex) {
                   // Report the exception to the user.
                  
                   ExceptionDialog.show(this, "Invalid rotation length: ", ex);
                }
             }



          塊和語(yǔ)句
          使用下面的方針來(lái)編寫(xiě)塊和語(yǔ)句:


          一行只寫(xiě)一個(gè)語(yǔ)句  
          控制語(yǔ)句總是使用{}這樣的括號(hào) (e.g., 'if').
          考慮在塊的末尾使用一個(gè)注釋 (e.g., } // end if), 尤其是長(zhǎng)的或嵌套塊
          在塊的開(kāi)頭放置變量的聲明語(yǔ)句  
          總記得初始化變量  
          如果你是個(gè)完美主義者,左對(duì)齊變量名
          在switch塊里縮進(jìn)case從句  
          在操作符后留有空白
          在if, for, 或while語(yǔ)句中, 在括號(hào)“(”前留有空白
          在表達(dá)式中使用空白和插入語(yǔ)來(lái)增強(qiáng)可讀性

          在for循環(huán)中的變量是個(gè)例外。 循環(huán)變量可能會(huì)在語(yǔ)句初始化部分被定義。 e.g., for (int i = 0; ...)

          .

          在塊的末尾插入注釋有助于你無(wú)意中跟蹤到被刪除的結(jié)尾括號(hào)“}”.

          Example 3. Bad Block Style.

          try{
                for(int i=0;i<5;i++){
                   ...
                   }
                int threshold=calculateThreshold();
                float variance=(threshold*2.8)-1;
                int c=0;
                if (threshold<=15) c=calculateCoefficient();
                switch(c){
                case 1: setCeiling(c*2); break;
                case 2: setCeiling(c*3); break;
                else: freakOut();
                }
             }catch(Exception ex){ ... }



          Example 4. Good Block Style.

          try {
                int   threshold  = 0;
                float variance    = 0.0;
                int   coefficient = 0;
                
                // Prepare 5 cycles.
                
                for (int i = 0; i < 5; i ++){
                   prepareCycle(i);
                }
                
                // Calculate the threshold and variance.
                
                threshold = calculateThreshold();
                variance = (threshold * 2.8) - 1;
                
                // If the threshold is less than the maximum, calculate the coefficient.
                // Otherwise, throw an exception.
                
                if (threshold <= MAX_THRESHOLD) {
                   coefficient = calculateCoefficient();
                } else {
                   throw new RuntimeException("Threshold exceeded!");
                }
                
                // Set the ceiling based on the coefficient.
                
                switch (coefficient) {
                   case 1:
                      setCeiling(coefficient * 2);
                      break;
                    
                   case 2:
                      setCeiling(coefficient * 3);
                      break;
                    
                   else:
                      freakOut();
                } // end switch
             } catch(Exception ex) {
                ...
             } // end try

          posted @ 2005-10-18 21:44 lemon 閱讀(540) | 評(píng)論 (0)編輯 收藏

          2005年10月9日 #

          關(guān)于BlogJava

             先在這里注冊(cè)了一個(gè)Blog,對(duì)這里的情況還不是很了解。期待以后本Blog有比較好的人氣吧,呵呵!

          posted @ 2005-10-09 10:29 lemon 閱讀(220) | 評(píng)論 (0)編輯 收藏

          僅列出標(biāo)題  
          主站蜘蛛池模板: 安泽县| 定南县| 凌云县| 鄂尔多斯市| 安溪县| 青阳县| 永平县| 呼和浩特市| 浪卡子县| 霍林郭勒市| 通城县| 米林县| 台南县| 原平市| 宜春市| 金门县| 磐石市| 镶黄旗| 广宗县| 奈曼旗| 玛纳斯县| 玉龙| 全州县| 宁津县| 泰来县| 谢通门县| 山东省| 澳门| 股票| 出国| 双桥区| 澄江县| 赣州市| 芷江| 江永县| 贵德县| 鄂尔多斯市| 尉氏县| 遵义市| 雷山县| 江达县|