class Initial{
private Scanner sc=new Scanner(System.in);
//整形數組的處理方法
public void initArr(int[] arr){
arr=new int[arr.length];
//爲數組元素賦值
for(int x=0;x<arr.length;x++){
System.out.println("請輸入第"+(x+1)+"個元素:");
arr[x]=sc.nextInt();
}
//顯示所有元素
System.out.print("所有元素:");
for(int x=0;x<arr.length;x++){
if(x==arr.length-1){
System.out.println(arr[x]);
}else{
System.out.print(arr[x]+", ");
}
}
}
//雙精度型數組處理方法
public void initArr(double[] arr){
arr=new double[arr.length];
//爲數組元素賦值
for(int x=0;x<arr.length;x++){
System.out.println("請輸入第"+(x+1)+"個元素:");
arr[x]=sc.nextDouble();
}
//顯示所有元素
System.out.print("所有元素:");
for(int x=0;x<arr.length;x++){
if(x==arr.length-1){
System.out.println(arr[x]);
}else{
System.out.print(arr[x]+", ");
}
}
}
//字符型數組處理方法
public void initArr(String[] arr){
arr=new String[arr.length];
//爲數組元素賦值
for(int x=0;x<arr.length;x++){
System.out.println("請輸入第"+(x+1)+"個元素:");
arr[x]=sc.next();
}
//顯示所有元素
System.out.print("所有元素:");
for(int x=0;x<arr.length;x++){
if(x==arr.length-1){
System.out.println(arr[x]);
}else{
System.out.print(arr[x]+", ");
}
}
}
}
public class InitialTest{
public static void main(String[] args){
//創建鍵盤錄入對象
Scanner sc=new Scanner(System.in);
//接收數據
System.out.print("請輸入數組元素個數:");
int num=sc.nextInt();
//定義數組
int[] arrInt=new int[num];
double[] arrDouble=new double[num];
String[] arrString=new String[num];
Initial it=new Initial();
System.out.println();
//菜單選項
System.out.println("請輸入相應數組元素類型前的數字:1.整形 2.雙精度型 3.字符串型");
System.out.println();
int d=sc.nextInt();
switch(d){
case 1:
it.initArr(arrInt);break;
case 2:
it.initArr(arrDouble);break;
case 3:
it.initArr(arrString);break;
default :
System.out.println("你輸入的數字有誤");
}
}
}