简体   繁体   English

如何解决这个简单的作用域错误?

[英]How can I fix this simple scoping error?

Having some issues with scoping. 在范围界定方面存在一些问题。 I am trying to write a program using a loop that takes 10 values representing exam grades (between 0 and 100) from the keyboard and outputs the minimum value, maximum value and average value of all the values entered. 我正在尝试使用一个循环编写程序,该循环从键盘获取代表考试成绩的10个值(0到100之间),并输出所有输入值的最小值,最大值和平均值。 My program cannot accept values less than 0 or greater than 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);
   }
 } 

My compiler error is that I cannot fix the scoping error: 我的编译器错误是我无法解决范围错误:

    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)
                          ^

To fix the scoping problem, move the declaration/initialization of x to a point before its first use: 要解决范围问题,请将x的声明/初始化移至首次使用之前的一点:

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

There are several problems with your code: 您的代码有几个问题:

  • if(scan.hasNextInt()) will be executed only before the first read of the int ; if(scan.hasNextInt())仅在第一次读取int之前执行; you should change your code to check for next int on each iteration of the loop 您应该更改代码以在循环的每次迭代中检查下一个int
  • You need to add variables for the current min , max , and total 您需要为当前的minmaxtotal添加变量
  • You do not need to store the values in the array, because the three scalars are enough to compute all three outputs required of your program. 您不需要将值存储在数组中,因为三个标量足以计算程序所需的所有三个输出。

Move x on top of the if. 将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;
      }
   }

You have declared x inside the if clause. 您已经在if子句中声明了x So when your program reaches the if , x won't be defined. 因此,当程序到达if ,将不会定义x Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM