1.申明
int [][] array1 ={ {1,2,3} , {0} , {2,2,2,2,2} , {5,6} }; 锯齿数组
int [][] array2 = new int [5][ ]; // new int[5][] 创建数组时,必须指定第一个下标标。语法new int[] []是错误的。
array2[0] = new int[3];
array2[1] = new int[6]; ...
2.二维数组的长度
int [][] x =new int [3][4];
x.length = 3 ;
x[0].length = x[1].length = x[2].length =4;
例子:选择题测验得分。用随机函数生成N个同学的选择题答案,保存在二维数组里。再随机生成一个正确答案,计算每位同学的正确率。
package basic_practice_003;
public class N_array { //多选题测验评分例子
final static int countIssue = 9;
final static int countStudent = 6;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(" 题目 :1 2 3 4 5 6 7 8 9");
char [][]student = new char[countStudent][countIssue];
char []rightAnswer = new char[countIssue];
getAnswer(rightAnswer);
getAnswer(student,rightAnswer);
}
public static void getAnswer(char [][]m,char []rightAnswer){
for(int j=0;j<countStudent;j++) {
System.out.print("student " + j + ":");
for(int i=0;i<countIssue;i++) {
m[j][i]=getRandomAnswer();
System.out.print(m[j][i] + " ");
}
int right =0;
for(int i=0;i<countIssue;i++){
if(m[j][i]==rightAnswer[i]) right++;
}
System.out.printf(" right rate = %.3f",right*1.0/countIssue);
System.out.println();
}
}
public static void getAnswer(char []m){
System.out.print("rightAns :");
for(int i=0;i<countIssue;i++) {
m[i]=getRandomAnswer();
System.out.print(m[i] + " ");}
System.out.println();
}
public static char getRandomAnswer(){
return(char)('A' + Math.random()*('D' - 'A' + 1));}
}
结果:
输入N点坐标点,找出距离最小的两点。
public class FindNearestPoints {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("1.enter the number of point:");
Scanner input = new Scanner(System.in);
int number_of_point = input.nextInt();
System.out.println("2.enter " +2*number_of_point +" point:");
double [][] point = new double[number_of_point][2];
System.out.println("enter "+ number_of_point*2+" points location:");
for(int i=0;i<number_of_point;i++) {
point[i][0] = input.nextDouble();
point[i][1] = input.nextDouble();
}
double nearestD = (point[0][0]-point[1][0])*(point[0][0]-point[1][0])+(point[0][1]-point[1][1])*(point[0][1]-point[1][1]);
int index1=0,index2=0;
for(int i=0;i<number_of_point;i++) {
for(int j=i+1;j<number_of_point;j++) {
double Distance = (point[i][0]-point[j][0])*(point[i][0]-point[j][0])+(point[i][1]-point[j][1])*(point[i][1]-point[j][1]);
if(Distance < nearestD) {
nearestD=Distance;
index1=i;
index2=j;
}
}
}
System.out.printf("the NearestPoints is (%.2f,%.2f),(%.2f,%.2f)",point[index1][0],point[index1][1],point[index2][0],point[index2][1] );
System.out.println();
System.out.println("the NearestD = " + Math.sqrt(nearestD));
}
}