作為程序員,思維要縝密,對(duì)于技術(shù)人員,創(chuàng)造只是一小部分,大部分還是要腳踏實(shí)地。
所以每個(gè)問(wèn)題一定要想到各種情況,測(cè)試人員可能會(huì)用你想不到的數(shù)據(jù)進(jìn)行測(cè)試。
練習(xí)1:計(jì)算某數(shù)的階乘!
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);
}
}
}

那么對(duì)于數(shù)據(jù)輸入的合法性判斷,對(duì)于數(shù)據(jù)是否合理,對(duì)于程序是否能夠計(jì)算所有的數(shù),有無(wú)上界。
記住,即使不能計(jì)算,也要告訴用戶,決不能給用戶提供錯(cuò)誤的答案!!
result 類型如果為int只能算到12,如果為long能算到20,如果為float只能算到32,如果為double,則可以算到170。
為什么double和long同占用8個(gè)字節(jié),為什么表示數(shù)的范圍差那么多?因?yàn)閐ouble類型支持科學(xué)計(jì)算法。
The factorial of 170 is 7.257415615307994E306
所以可能用指數(shù)方式來(lái)表達(dá)大數(shù)。
那么如果表示170以后的數(shù)的階乘呢?可以猜用類,也可以找兩個(gè)變量,一個(gè)存底數(shù),一個(gè)存指數(shù)。
=================================
數(shù)組
int[] mark = new int[10];40字節(jié)存儲(chǔ)空間。
-----------------------
對(duì)于局部變量,需要初始個(gè)值。
而局部變量的數(shù)組,不需要初值,會(huì)根據(jù)類型給定相應(yīng)默認(rèn)值。數(shù)值為0/0.0,布爾false,對(duì)象null,char /u0000
----------------------
mark 是一個(gè)int[]數(shù)組類型的對(duì)象,它保存的是那40字節(jié)存儲(chǔ)空間的首地址。
Java中,引用和地址都保存在棧中,而具體的值開辟的空間存儲(chǔ)在堆中。
System.arraycopy(a,0,b,0,a.length);
int[] a = {1,2,3,4,5}
int[] b = new int[10];
a.length
數(shù)組特點(diǎn)
1.不可變長(zhǎng)
2.可以保存簡(jiǎn)單類型數(shù)據(jù)
3.查找快,插入和刪除效率低。
2維數(shù)組
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類型?是一個(gè)對(duì)象,但是是虛擬機(jī)級(jí)別對(duì)象,無(wú)法用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;
}
}
