我刚开始学习循环,但每当我尝试执行程序时,我都会遇到同样的问题。同样,即使是我教授的程序示例也会出现同样的错误。这是程序,它只是我正在练习的程序
import java.util.Scanner;
public class BaseballStats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SENTINEL = 0;
int hrs = 0;
int count = 0;
do
{
System.out.print("Enter the number of home runs from each team: ");
int homeruns = in.nextInt();
if(homeruns > 0)
{
hrs = hrs + homeruns;
count++;
}
}
while(homeruns != SENTINEL);
System.out.print("The average amount of home runs per team is: ");
System.out.println(hrs / count);
}
}
我继续使用这个程序和我尝试的每个其他循环程序的问题是括号内的变量(homeruns)在括号外没有定义。
while(homeruns!= SENTINEL);简单地说明符号变量homeruns不存在,如果我在程序开头初始化它,它就不会在括号内工作,因为它会说变量已经存在。
我不知道我是不是听起来像个白痴,但我真是太难以置信了。
答案 0 :(得分:5)
在循环外声明它,然后不在循环内重新声明它:
int homeruns;
do
{
System.out.print("Enter the number of home runs from each team: ");
//int homeruns = in.nextInt();
homeruns = in.nextInt();
if(homeruns > 0)
{
hrs = hrs + homeruns;
count++;
}
}
while(homeruns != SENTINEL);