作為程序員,思維要縝密,對于技術人員,創造只是一小部分,大部分還是要腳踏實地。
所以每個問題一定要想到各種情況,測試人員可能會用你想不到的數據進行測試。
練習1:計算某數的階乘!
package com.ljl;


public class Factorial
{
public static void main(String[] args)

{

try
{
int num = Integer.parseInt(args[0]);
if(num < 0)

{
System.out.println("please input positive number!");
System.exit(0);
}
if(num > 170)

{
System.out.println("this program can't calculate this num!");
System.exit(0);
}
double result = 1d;
for(int i = 2; i <= num; i++)

{
result *= i;
}
System.out.println("The factorial of " + num + " is " + result);
}
catch(Exception ex)

{
if(ex instanceof ArrayIndexOutOfBoundsException)

{
System.out.println("Please input the num to calculate!");
System.exit(0);
}
if(ex instanceof NumberFormatException)

{
System.out.println("Please input a number!");
System.exit(0);
}
System.out.println("error occured!please run it again!");
System.exit(0);
}
}
}

那么對于數據輸入的合法性判斷,對于數據是否合理,對于程序是否能夠計算所有的數,有無上界。
記住,即使不能計算,也要告訴用戶,決不能給用戶提供錯誤的答案!!
result 類型如果為int只能算到12,如果為long能算到20,如果為float只能算到32,如果為double,則可以算到170。
為什么double和long同占用8個字節,為什么表示數的范圍差那么多?因為double類型支持科學計算法。
The factorial of 170 is 7.257415615307994E306
所以可能用指數方式來表達大數。
那么如果表示170以后的數的階乘呢?可以猜用類,也可以找兩個變量,一個存底數,一個存指數。
=================================
數組
int[] mark = new int[10];40字節存儲空間。
-----------------------
對于局部變量,需要初始個值。
而局部變量的數組,不需要初值,會根據類型給定相應默認值。數值為0/0.0,布爾false,對象null,char /u0000
----------------------
mark 是一個int[]數組類型的對象,它保存的是那40字節存儲空間的首地址。
Java中,引用和地址都保存在棧中,而具體的值開辟的空間存儲在堆中。
System.arraycopy(a,0,b,0,a.length);
int[] a = {1,2,3,4,5}
int[] b = new int[10];
a.length
數組特點
1.不可變長
2.可以保存簡單類型數據
3.查找快,插入和刪除效率低。
2維數組
int[][] a = {{1,2},{3,4},{5,6}};
int[][] a = new int[3][];
a[0] = new int[2];
a[1] = new int[3];
a[2] = new int[1];
a類型?是一個對象,但是是虛擬機級別對象,無法用getClass().getName()顯示。
哥德巴赫猜想
package com.ljl;


public class Goldbach
{
public static void main(String[] args)

{
int num = Integer.parseInt(args[0]);
if(num < 6)

{
System.out.println("the num must larger than six!");
System.exit(0);
}
if(num%2 != 0)

{
System.out.println("it should be a even!");
System.exit(0);
}
for(int i = 1; i <= num/2; i++)

{

if(isZhiShu(i)&&isZhiShu(num-i))
{
System.out.println(num + "=" + i + "+" + (num-i));
break;
}
}
}
private static boolean isZhiShu(int num)

{
for(int i = 2; i <= (int)Math.sqrt(num); i++)

{
if(num%i == 0)
return false;
}
return true;
}
}

posted on 2005-11-25 23:35
北國狼人的BloG 閱讀(304)
評論(0) 編輯 收藏 所屬分類:
達內學習總結