【问题标题】:How can I fix this simple scoping error?如何解决这个简单的范围错误?
【发布时间】:2023-03-31 23:08:01
【问题描述】:

在范围界定方面存在一些问题。我正在尝试使用一个循环编写一个程序,该循环从键盘获取 10 个代表考试成绩(0 到 100 之间)的值,并输出所有输入值的最小值、最大值和平均值。我的程序不能接受小于 0 或大于 100 的值。

import java.util.Scanner; 
import java.util.Arrays;

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

       int MAX = 100;
       int MIN = 0;
       int[] grades = new int[10];


       System.out.println("Please enter the grades into the gradebook.");
       if(scan.hasNextInt())
       {
         for (int i = 0; i < grades.length; i++)
          {
             if( x>MIN && x<MAX)
             {
             int x = scan.nextInt();
             grades[i] = x;
          }
       }
    }  
       System.out.print("The grades are " + grades.length);
   }
 } 

我的编译器错误是我无法修复范围错误:

    ExamBookClient.java:21: error: cannot find symbol
             if( x>MIN && x<MAX)
                 ^
  symbol:   variable x
  location: class ExamBookClient
ExamBookClient.java:21: error: cannot find symbol
             if( x>MIN && x<MAX)
                          ^

【问题讨论】:

  • 在 x 范围内之前不要使用它。提前声明。

标签: java arrays loops scope


【解决方案1】:

要解决范围问题,请将x 的声明/初始化移动到第一次使用之前的某个点:

int x = scan.nextInt();
if( x>MIN && x<MAX ) {
    grades[i] = x;
}

你的代码有几个问题:

  • if(scan.hasNextInt()) 只会在第一次读取int 之前执行;您应该更改代码以在循环的每次迭代中检查下一个 int
  • 您需要为当前minmaxtotal添加变量
  • 您不需要将值存储在数组中,因为三个标量足以计算程序所需的所有三个输出。

【讨论】:

    【解决方案2】:

    将 x 移到 if 之上。

    if(scan.hasNextInt())
       {
         for (int i = 0; i < grades.length; i++)
          {
             int x = scan.nextInt();
             if( x>MIN && x<MAX)
             {
    
             grades[i] = x;
          }
       }
    

    【讨论】:

      【解决方案3】:

      您在if 子句中声明了x。所以当你的程序到达if 时,x 将不会被定义。试试这个:

      int x = scan.nextInt(); // OUTSIDE THE IF
      if( x > MIN && x < MAX)
      {        
          grades[i] = x;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-20
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多