繁体   English   中英

通过使用“嵌套” FOR循环访问矩阵来填充ArrayList

[英]Fill the ArrayList by accessing the matrix using a ‘nested’ FOR loop

使用挑战8中的矩阵和ArrayList设计,创建一个数组总计,以容纳5个学生中每个学生的总成绩。 通过使用“嵌套的” FOR循环结构访问矩阵来填充ArrayList(i将移动,j将移动)。 填写总计数组后,确定总计最高的学生的姓名,并注明其姓名和平均分数(小数点后一位)。

如何将学生的总成绩从矩阵添加到ArrayList的单个位置?

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    ArrayList<String> names = new ArrayList<String>();
    ArrayList<Integer> total = new ArrayList<Integer>();
    int [][] scores = new int [5][6];
    int score = 0;

    for (int i = 0; i < 5; i++) {
        System.out.print("Enter " + "(" + (i+1) + ") friend's name: ");
        names.add(input.nextLine());
    }

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 6; j++) {
            score = 1 + (int)(Math.random() * ((20 + 1)));
            scores[i][j] = score;   
        }
        total.add(i,0);
    }
}

只需保留行的总和,然后将其插入total组即可

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    ArrayList<String> names = new ArrayList<String>();
    ArrayList<Integer> total = new ArrayList<Integer>();
    int [][] scores = new int [5][6];
    int score = 0;

    for (int i = 0; i < 5; i++) {
        System.out.print("Enter " + "(" + (i+1) + ") friend's name: ");
        names.add(input.nextLine());
    }

    for (int i = 0; i < 5; i++) {
        int tlsc = 0;
        for (int j = 0; j < 6; j++) {
            score = 1 + (int)(Math.random() * ((20 + 1)));
            tlsc+=score;
            scores[i][j] = score;   
        }
        total.add(tlsc);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM