有谁能告诉我这段代码我做错了什么?
public class grades {
public static void main(String[] args) {
int[] testMarks = Marks.getMarks();
System.out.print(grading(testMarks));
}
public static char[] grading(int[] testMarks) {
char grade = '0';
char[] grades = new char[grade];
int value = 0;
int n = 0;
while (n < testMarks.length) {
value = testMarks[n];
if (value >= 90) {
grade = 'A';
}
else if (value < 90 && value >= 75) {
grade = 'B';
}
else if (value < 75 && value >= 60) {
grade = 'C';
}
else if (value < 60 && value >= 50) {
grade = 'D';
}
else if (value < 50 && value >= 45) {
grade = 'E';
}
else {
grade = 'F';
}
n =+ 1;
}
return grades;
}
}
我试图根据列出的边界将testMarks数组的值作为char返回。我没有收到任何错误,但它没有显示任何内容。
干杯, EM
答案 0 :(得分:3)
n =+ 1
将是n += 1
。char[] grades = new char[grade]
将为char[] grades = new char[testMarks.length]
grades[n] = grade
答案 1 :(得分:1)
您忘记填写成绩数组:)您需要:
grades[n] = grade;
在递增n之前;否则grade数组将为空。除此之外,n ++可以正常工作:
public static char[] grading(int[] testMarks) {
char grade = '0';
char[] grades = new char[testMarks.length];
int value = 0;
int n = 0;
while (n < testMarks.length) {
value = testMarks[n];
if (value >= 90) {
grade = 'A';
}
else if (value < 90 && value >= 75) {
grade = 'B';
}
else if (value < 75 && value >= 60) {
grade = 'C';
}
else if (value < 60 && value >= 50) {
grade = 'D';
}
else if (value < 50 && value >= 45) {
grade = 'E';
}
else {
grade = 'F';
}
grades[n] = grade;
n++;
}
return grades;
}
答案 2 :(得分:0)
也许你应该在你的代码中写n + = 1
答案 3 :(得分:0)
grades
数组始终为空。您需要在返回之前将grade
值存储在该数组中。这样的事情应该有效:
public static char[] grading(int[] testMarks) {
char grade = '0';
char[] grades = new char[testMarks.length]; // initialise with an empty char array with the same length as testMarks
int value = 0;
int n = 0;
while (n < testMarks.length) {
value = testMarks[n];
if (value >= 90) {
grade = 'A';
}
else if (value < 90 && value >= 75) {
grade = 'B';
}
else if (value < 75 && value >= 60) {
grade = 'C';
}
else if (value < 60 && value >= 50) {
grade = 'D';
}
else if (value < 50 && value >= 45) {
grade = 'E';
}
else {
grade = 'F';
}
grades[n] = grade; // store the grade in the grades array
n += 1;
}
return grades;
}