20165235 祁瑛 Java第四周考試總結

來源:互聯網
上載者:User

標籤:函數   功能   迴圈   can   ext   分享   continue   commit   pre   

20165235 祁瑛 Java第四周考試總結課後習題p29 p45
  • 代碼編寫
  • import java.util.*;class Example2_5{  public static void main (String args[]){ int start = 0,end ,middle; int a[] = {12,45,67,89,123,-45,67}; int N = a.length; for(int i=0;i<N;i++){ for(int j=i+1;j<N;j++){   if(a[j] < a[i] ){     int t = a[j];     a[j] = a[i];     a[i] = t;   } }   } Scanner scanner = new Scanner(System.in); System.out.println("輸入一個整數,程式判斷該數是否在數組中:"); int number = scanner.nextInt(); int count =0; end = N; middle=(start+end)/2; while(number!=a[middle]){    if(number>a[middle])      start = middle;    else if (number < a[middle])      end = middle;    middle = (start+end)/2;    count++;    if(count>N/2)      break;   }    if(count>N/2)      System.out.printf("%d buzaishuzuzhong.\n",number);    else      System.out.printf("%d zaishuzuzhong.\n",number);   }}
    public class Example3_7{   public static void main (String args[]){ int sum =0,i,j; for(i=1;i<=10;i++){   if(i%2==0){   continue; } sum=sum+i;} System.out.println("sum="+sum);  for(j=2;j<=100;j++){ for(i=2;i<=j/2;i++){     if(j%i==0)       break; }   if(i>j/2){ System.out.println(""+j+"是素數"); }   } }}
  • 在本次考試中因為我的上傳失敗,導致未能交上實驗結果,可能是用QQ的原因。本次代碼在第二周時已經敲好,如下為
  • p29代碼串連
  • p45代碼串連。
  • 運行如下:
  • 遞迴與迴圈

    本次實驗讓我們通過編程實現1!+2!+3!+.....+n!的功能。代碼如下:

 public class A{     public static void main(String args[]){      int [] a = new int [args.length];      for(int i =0;i<args.length;i++){         a[i] = Integer.parseInt(args[i]);      }      int sum = 0;      if(args.length<1){          System.out.println(" 輸入有誤! ");          System.exit(0);        }       for(int i =1;i<=a[0];i++){          sum += fact(i);        }        if (sum<=0){          System.out.println(" 輸入有誤! ");          System.exit(0);        }      System.out.println(sum);  }      public static int fact(int n) {        if (n == 0)            return 1;        else            return n * fact(n-1);     }}
  • 這個程式利用遞迴實現了階乘的和,其中a[i] = Integer.parseInt(args[i])把輸入的資料存放在數組中,在遞迴運算時只調用a[0]中的數值去計算,如果數組長度小於1或輸入負數則通過System.exit(0)退出程式。
  • 下面的是運行:
  • 以下是碼雲代碼串連。

    考試內容總結
  • 在用JDB調試代碼得輸入jdb -classpath .:./bin A 3,然後對函數設定斷點,使用next或使用step進行單步運行。
  • 如果想列印sum的值可以使用print sum來進行觀察.

    第二三章編程題代碼
  • 第三四章編程代碼串連。
  • 代碼運行結果圖:

  • -

20165235 祁瑛 Java第四周考試總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.