Lecture1 二維數組的應用
public class ArrayDemo {
public static void main(String[] args) {
//二維數組的聲明--三種形式
//聲明int類型的二維數組
int[][] intArray;
//聲明float類型的二維數組
float floatArray[][];
//聲明double類型的二維數組
double[] doubleArry[];
//建立一個int類型的四行兩列的二維數組
intArray = new int[4][2];
//爲第三行第二個元素賦值爲3
intArray[2][1] = 3;
//聲明數組的同時進行建立
char[][] ch = new char[3][5];
//建立二維數組時,能夠只指定行數
float[][] floats = new float[3][];
//System.out.println(floats[0][0]); 空指針異常,解決方法以下:
//二維數組每行至關於一個一維數組
floats[0] = new float[3];//第一行有三列
floats[1] = new float[4];//第二行有四列
floats[2] = new float[5];//第三行有五列
System.out.println(floats[0][0]);//此時解決空指針異常問題
//System.out.println(floats[0][3]); 數組下標越界
//二維數組初始化
System.out.println("============================");
int[][] num1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("num1數組第一行第二列的元素爲:" + num1[0][1]);
System.out.println("num1數組的行數爲:" + num1.length);
System.out.println("num1數組的列數爲:" + num1[0].length);
int[][] num2 = {{1}, {2, 3}, {4, 5, 6, 7}};
System.out.println("num2數組第一行的列數爲:" + num2[0].length);
//循環輸出二維數組的元素
System.out.println("============================");
for (int i = 0; i < num2.length; i++) {
for (int j = 0; j < num2[i].length; j++) {
System.out.print(num2[i][j] + " ");
}
System.out.println();
}
//使用加強型for循環輸出二維數組
System.out.println("============================");
for (int[] array : num2) {
for (int n : array) {
System.out.print(n + " ");
}
System.out.println();
}
}
}
import java.util.Scanner;
/**
* 使用二維數組統計並計算學生的成績總分和平均分
*/
public class quiz1_5 {
public static void main(String[] args) {
int[][] intArray = new int[3][2];
int sumChinese = 0, sumMath = 0;
int avgChinese = 0, avgMath = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
System.out.println("請輸入第" + (i + 1) + "個學生的語文成績:");
intArray[i][0] = sc.nextInt();
System.out.println("請輸入第" + (i + 1) + "個學生的數學成績:");
intArray[i][1] = sc.nextInt();
sumChinese += intArray[i][0];
avgChinese = sumChinese / (i + 1);
sumMath += intArray[i][1];
avgMath = sumMath / (i + 1);
}
System.out.println("語文的總成績爲:" + sumChinese);
System.out.println("語文的平均分爲:" + avgChinese);
System.out.println("數學的總成績爲:" + sumMath);
System.out.println("數學的平均分爲:" + avgMath);
}
}
祝你們新年快樂,狗年旺旺^_^