import java.io.*;
public class IOStreamDemo
{
public static void main(String[] args) throws IOException
{
/*BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int n = Integer.parseInt(str);*/
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the length of the array:");
String str = stdin.readLine();;
System.out.println(str);
int n = Integer.parseInt(str);
int[] a = new int[n];
System.out.println("Enter "+n+" numbers to initiate the array:");
for(int i=0;i<n;i++)
{
String s = stdin.readLine();//可以直接利用變量stdin而不用再重新定義。
a[i] = Integer.parseInt(s);//強制類型轉換
}
System.out.println("The array is:");
for(int i=0;i<n;i++)
{
System.out.println("a["+i+"]="+a[i]);
}
int[] b;
java.util.Arrays.sort(a);
b = a;
System.out.println("After sorted:");
for(int i=0;i<n;i++)
{
System.out.println("b["+i+"]="+b[i]);
}
}
}
**********************************************************
關於數組的初始化(從鍵盤讀入value值)
BufferedReader br = new BufferedRead(new InputStreamReader(System.in));
String str = br.readLine(); //讀入的是一個char類型的字符
int i = Integer.parseInt(str);//將str強制轉化成int型的。
或者:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str;
str = br.readLine();
int i;
i = Integer.parseInt(str);
下面數組的元素賦值可以利用一個循環語句分別對其賦值。對鍵盤的操作語句基本上同上面一樣~
這是最基本的數組元素的初始化問題,以後經常用到,應該很熟練的掌握。還有一個很常用的數組
的排序函數:
java.util.Arrays.sort(a);//對已經初始化的數組a進行排序,排序結果還是存在a中,
不好的地方是破壞了原來的數組a。當遇到類似按學生成績排名次的問題時候還要另當考慮~