我很难过,因为Java无法找到我的数组[]是因为我在do-while循环中声明了它?但是当我在do-while循环之外声明它时,它有错误。你能救我吗?
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//Input number of grades.
System.out.print("Enter No. of Grades from 5-10: ");
int grades=0;
do{
grades=in.nextInt();
int a[]=new int[grades];
for(int i=0; i<grades; i++){
//Inputing the grades
System.out.print("Grades Values: ");
int temp=0;
//checking whether the no. grades are less than 5 or more than 10
if(grades>11 || grades<5){
System.out.println("INVALID!!");
System.out.println("Enter Valid Number of Grades: ");
}
do{
temp=in.nextInt();
//checking whether the user's input of grades' values is between 0 to 100
if(temp<0 || temp>=101){
System.out.println("Invalid Grade!");
System.out.println("Enter Valid Grade: ");
}
}while(temp<0 || temp>=101);
a[i]=temp;
}
}while(grades>11 || grades<5);
//getting Highest grade
int highest=a[0];
for(int i=1; i<a.length;i++){
if(a[i]>highest){
highest=a[i];
}
}
System.out.println(highest);
}
答案 0 :(得分:1)
是因为我在do-while循环中声明了它吗?
是
do {
int[] a;
}
...
// a is not visible here, because it is declared within the do-block.
但是当我在do-while循环之外声明它时它有错误
这取决于你是如何做到的。这应该有效:
int[] a;
do {
grades = in.nextInt();
a = new int[grades];
...
}