Anonymous

# JAVA新手一些問題，如何寫出5x5陣列與相關變化

int [][] a = {{1,2,3,4,5},

{6,7,8,9,10},

{11,12,13,14,15},

{16,17,18,19,20},

{21,22,23,24,25}};

Rating
• ?
Lv 7

請參考我的做法

public class Y12126 {

public static void main(String[] args) {

// generate 25 non-duplicate integers

int[] ary1 = new int[25];

for (int i = 0; i < ary1.length; i++) {

while (true) {

int x = (int)(Math.random() * 51) + 50;

if (noDuplicate(ary1, x)) {

ary1[i] = x;

break;

}

}

}

// populate to 5x5 array with sum/average calculation

int[][] ary2 = new int[5][5];

int[] sums = new int[5];

double[] avgs = new double[5];

for (int i = 0; i < ary2.length; i++) {

int sum = 0;

for (int j = 0; j < ary2[i].length; j++) {

ary2[i][j] = ary1[i*5+j];

sum += ary2[i][j];

}

sums[i] = sum;

avgs[i] = sum/5.0D;

}

// Print out

for (int i = 0; i < ary2.length; i++) {

System.out.print(java.util.Arrays.toString(ary2[i]));

System.out.println("\tSum: " + sums[i] + "\tAverage: " + avgs[i]);

}

}

public static boolean noDuplicate(int[] ary, int x) {

for (int i = 0; i < ary.length; i++) {

if (x == ary[i]) return false;

}

return true;

}

}

private int[][] array; //二元陣列

private int size; //陣列大小(size*size)

public Matrix(int value){ //建構子

size=value;

array=new int[size][size];

}

public static void show(Matrix m){ //亂數給值(50~100)

for (int i=0;i<m.size;i++){

for (int j=0;j<m.size;j++){

m.array[i][j]=(int) (Math.random()*51)+50;

System.out.print("A["+i+"]["+j+"]: "+m.array[i][j]+"\t");

}

System.out.println();

}

}

public static void rows(Matrix m){ //每列加總及總合平均值

int[] c=new int[m.size];

for (int i=0;i<m.size;i++){

for (int j=0;j<m.size;j++){

c[i]+=m.array[j][i];

}

System.out.print("R["+i+"]: "+c[i]+"\t");

}

System.out.println();

//列平均

double result=0;

for (int d:c){

result+=d;

}

result=result/m.size;

System.out.println("列平均: "+result);

}

public static void getTransPose(Matrix m1,Matrix m2){ //置換陣列m1->m2

for(int i=0;i<m1.size;i++){

for (int j=0;j<m1.size;j++){

m2.array[i][j]=m1.array[j][i];

System.out.print("T["+i+"]["+j+"]: "+m2.array[i][j]+"\t");

}

System.out.println();

}

}

public static void main(String[] args){ //主程式

Matrix m=new Matrix(5);

Matrix m1=new Matrix(4);

Matrix m2=new Matrix(4);

show(m);

show(m1);

rows(m1);

getTransPose(m1,m2);

rows(m2);

}

}

您參考看看QQ,不過亂數值"可能"會重覆.

2008-04-06 23:56:34 補充：

在下的列平均是全部,若想要每列的得修改一下.