數組初始化及其遍歷

import java.util.Scanner;

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("你輸入的數字有誤");
}
}
}
發佈了34 篇原創文章 · 獲贊 21 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章