top
Loading...
數組在Java編程中的應用
天極IT資訊短信服務 電腦小技巧
資費:包月5元
手機:
介紹:細處著手,巧處用功。高手和菜鳥之間的差別就是:高手什么都知道,菜鳥知道一些。電腦小技巧收集最新奇招高招,讓你輕松踏上高手之路。




數組是很重要的數據結構,由同一類型相關的數據結構組成是靜態實體,有鏈表,隊列,堆棧,數等數據結構,java還提出了類數組的類vector。這些都是java數據結構的組成部分,正如我們學過的c語言版的數據結構,java數據結構也是來描述數據結構的只是描述語言是java一樣而已。

1.數組中最重要的是數組下標,數組下標及數組名是用來給訪問者提供訪問數組的途徑,數據下標從0開始,c[0],就是一個第一個數據第一個元素是c[i-1],數組名的名名規則與變量相同,其訪問格式也很簡單。

例:c.lenth就是數組的長度。

c[a+b]+=2 就是個數組a+b的值+2,在此數組也有易混淆的地方,那就是數組的第7個元素和數組元素7是兩個不相同的概念,初學者一定要區分其區別。

2.空間分配:任何數據都要占用空間,數組也不例外,java中用new來給一個新的數組分配空間。

例:

int c[ ]=new int[12];

其格式等同于

int c[];
c=new int[12];

他們的初始化值都是0。

一個數組可以同時聲明多個數組:

例:

string b[ ]=new String[100],x[ ]=new String[27];

數組可以聲明任何數據類型,double string ..

舉個例子來分析:


// Fig. 7.5: InitArray.java
// initialize array n to the even integers from 2 to 20
import javax.swing.*;
public class InitArray {
public static void main( String args[] )
{
final int ARRAY_SIZE = 10;
int n[]; // reference to int array
String output = "";

n = new int[ ARRAY_SIZE ]; // allocate array

// Set the values in the array
for ( int i = 0; i < n.length; i++ )
n[ i ] = 2 + 2 * i;

output += "SubscriptValue";

for ( int i = 0; i < n.length; i++ )
output += i + "" + n[ i ] + "";

JTextArea outputArea = new JTextArea( 11, 10 );
outputArea.setText( output );

JOptionPane.showMessageDialog( null, outputArea,
"Initializing to Even Numbers from 2 to 20",
JOptionPane.INFORMATION_MESSAGE );

System.exit( 0 );
}
}

程序中:

1.final int ARRAY_SIZE=10限定詞final聲明常數變量ARRAY_SIZE其值是10。

2. n = new int[ ARRAY_SIZE ]聲明了n數組其長度不能超過10

3.for ( int i = 0; i < n.length; i++ ) n[ i ] = 2 + 2 * i; 指定了程序的方法即輸出10個從2開始的偶數.其下標分別計為0-9的10個數。

4.output += "SubscriptValue";
for ( int i = 0; i < n.length; i++ )
output += i + "" + n[ i ] + ""; 在output后面追加字符串.顯示數組下標即計算結果.

5 JTextArea outputArea = new JTextArea( 11, 10 );
outputArea.setText( output );

創建一個新的文本框,把output放入其中.

JOptionPane.showMessageDialog( null, outputArea,"Initializing to Even Numbers from 2 to 20",JOptionPane.INFORMATION_MESSAGE );

作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗