在这里编码新手。我确信我的代码效率低下,并且可能会使用大量的代码。
现在回答我的问题。
我需要为数组中的X个项目输入用户输入,然后打印该数组,对每个项目进行评分。
输出应该看起来像"学生[数组位置]得分[该数组位置的值]。"
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the number of test scores: ");
int tests = input.nextInt();
int [] scores = new int [tests];
System.out.print("Enter " + tests + " scores: ");
for (int i = 0; i < tests; i++) {
scores[i] = input.nextInt();
int best = scores[0];
for (int j = 1; j < scores.length; j++) {
if (scores[j] > best) best = scores[j];
int gradeA = best - 10;
int gradeB = best - 20;
int gradeC = best - 30;
int gradeD = best - 40;
if (scores[i] >= gradeA){
System.out.print("Student " + scores[j] +" score is "
+ scores[i] + " and grade is A.");
}
else if (scores[i] <= gradeB){
System.out.print("\nStudent " + scores[j] +" score is "
+ scores[i] + " and grade is B.");
}
else if (scores[i] <= gradeC){
System.out.print("\nStudent " + scores[j] +" score is "
+ scores[i] + " and grade is C.");
}
else if (scores[i] <= gradeD){
System.out.print("\nStudent " + scores[j] +" score is "
+ scores[i] + " and grade is D.");
}
else{
System.out.print("\nStudent " + scores[j] +" score is "
+ scores[i] + " and grade is F.");
}
}
}
}
}
我得到的输出看起来很疯狂:
输入考试成绩数:5 输入5得分:45 78 82 56 74 学生0分为45分,分数为A.学生0分为45分,分数为A.学生0分为45分,分数为A.学生0分为45分,分数为A.学生78分为78分,分数为A.学生0分为78分,分数为A.学生0分为78分,年级为A.学生0分为78分,年级为A.学生78分为82分,分数为A.学生82分为82分,分数为A.学生0分为82分,分数为A.学生0分为82分,分数为A. 学生78分为56分,分数为B. 学生82分为56分,分数为B. 学生56分为56分,分数为B. 学生0分为56分,分数为B.学生78分为74分,分数为A.学生82分为74分,年级为A.学生56分为74分,分数为A.学生74分为74分,分数为A.
简单地说,如何修复我的代码以打印5个整齐的行格式(&#34;学生[数组位置]得分[该数组位置的值]。&#34;)。
答案 0 :(得分:1)
完成循环
System.out.print("Enter " + tests + " scores: ");
for (int i = 0; i < tests; i++) {
scores[i] = input.nextInt();
} // <------------- Finish loop here.
在此完成
for (int j = 1; j < scores.length; j++) {
if (scores[j] > best) best = scores[j];
} // <------------- Finish loop here.
计算成绩后再次启动它。
int gradeD = best - 40;
for (int i = 0; i < tests; i++) { // <------------- Started again.
if (scores[i] >= gradeA){
<强>替换强>
System.out.print("Student " + scores[j] +" score is "
+ scores[i] + " and grade is A.");
<强>与强>
System.out.println("Student " + i +" score is "
+ scores[i] + " and grade is A.");
快乐格式化。
祝你好运。