首页 > 解决方案 > Java:我不明白为什么这不起作用

问题描述

对 Java 来说是全新的。任务是创建一个 StudentGrades 应用程序,提示用户本学年完成的课程数量,然后提示用户输入每门课程的成绩。然后,StudentGrades 应用程序应在一行中显示有资格获得高成就奖 (>93) 的成绩,在下一行显示需要改进的成绩 (<70)。

输出显示如下:

/StudentGrade.java:46: error: cannot find symbol
        if(scores[i]<70) {
                  ^
  symbol:   variable i
  location: class StudentGrade
/StudentGrade.java:47: error: cannot find symbol
        System.out.print(scores[i]+ " ");
                                ^
  symbol:   variable i
  location: class StudentGrade
2 errors

我应该怎么办?我很困扰

这是我的代码:

import java.util.Scanner;

public class StudentGrade {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter the total number of courses
        System.out.print("Enter the number of courses completed this school year: ");
        int[] scores = new int[input.nextInt()];

        // Prompt the user to enter all the scores
        System.out.print("Enter " + scores.length + " score(s): ");
        for (int i = 0; i < scores.length; i++) {
            scores[i] = input.nextInt();
        }

        System.out.println("Grades that qualify for High Achievement Award (above 93%): ");
    for(int i=0; i< scores.length; i++) {
        if(scores[i]>93) {
            System.out.print(scores[i]+ " ");
        }}

    System.out.println("");
    System.out.println("Grades that need improvement (below 70%): ");
    for(int l=0; l<scores.length;l++) {
        if(scores[i]<70) {
        System.out.print(scores[i]+ " ");
        }

    }
    }

}

标签: java

解决方案


在这个循环中:

for(int l=0; l<scores.length;l++) {
    if(scores[i]<70) {
    System.out.print(scores[i]+ " ");
    }

您不用i作变量名,您已将其切换为l.

您的变量只存在于它们各自的范围内,这意味着一旦 for 循环开始,就没有更多的i.

将您的代码更改为:

for(int l=0; l<scores.length;l++) {
    if(scores[l]<70) {
    System.out.print(scores[l]+ " ");
    }

然后再试一次。


推荐阅读