gpt4 book ai didi

java - 对数组使用 if 语句

转载 作者:行者123 更新时间:2023-11-29 04:47:57 25 4
gpt4 key购买 nike

在注释步骤4我试图将当前数组元素添加到sum中,将当前数组元素与max_test进行比较,如果它更大,则将其保存在变量max_test中。并将当前元素与 min_test 进行比较,如果较小,则将其保存在 min_test 中。但是我不断收到错误

Grades5.java:55: error: bad operand types for binary operator '>'
if (grades[r] > grades[max_test])
^
first type: int[]
second type: int[]

Grades5.java:57: error: bad operand types for binary operator '<'
if (grades[r] < grades[min_test])
^
first type: int[]
second type: int[]

Grades5.java:59: error: bad operand types for binary operator '+'
sum += grades[r];
^
first type: int
second type: int[]

3 errors

代码:

 import java.util.Scanner;

public class Grades5
{
public static void main(String[] args)
{
int[][] grades = {
{ 87, 96, 100},
{ 68, 75, 72},
{ 99, 100, 95},
{100, 96, 70},
{ 75, 60, 79},
};
int how_many_grades = grades.length * grades[0].length;

// -----------------
// Output the grades
// -----------------
System.out.print(" ");
for (int i = 0; i < grades[0].length; i++)
System.out.print("Test " + (i + 1) + " ");
System.out.println("Average");
for (int r = 0; r < grades.length; r++)
{
int sum = 0; // Sum of one student's tests

// -------------------
// Process one student
// -------------------
System.out.print("Student " + (r + 1) + " ");
for (int c = 0; c < grades[r].length; c++)
{
System.out.printf("%6d ", grades[r]); // Step 1
//sum += grades[c]; // Step 2
}
System.out.printf("%7.2f\n", (double)sum / grades[r].length);
}

// ----------------
// Output a summary
// ----------------
int max_test, // Maximum test score
min_test, // Minimum test score
sum = 0; // Sum of all student tests

max_test = min_test = grades[0][0]; // Step 3
for (int r = 0; r < grades.length; r++)
{
// -------------------
// Process one student
// -------------------
for (int c = 0; c < grades[r].length; c++)
{
// Step 4
if (grades[r] > grades[max_test])
max_test = c;
if (grades[r] < grades[min_test])
min_test = c;
sum += grades[r];
}
}
System.out.println("Highest test score: " + max_test);
System.out.println("Lowest test score: " + min_test);
System.out.printf("Average test score: %.1f\n",
(double)sum / how_many_grades);
}
}

最佳答案

您的问题是 grades[r] 不是整数。它是整数的数组。你必须处理两个索引

sum += grades[i][j];

为了摆脱编译错误。

其他错误似乎是一样的。大体上可以这样想象:

grades[1] -> { 87,  96, 100}
grades[2] -> { 68, 75, 72}

grades[1][1] -> 87;
grades[1][2] -> 96;

等..

关于java - 对数组使用 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com