提问人:TheTargetAudience 提问时间:9/29/2022 最后编辑:TheTargetAudience 更新时间:9/29/2022 访问量:88
使用 scanner 使用 if 语句初始化局部变量
Initializing local variable with an if statement using scanner
问:
public class calGrades
{
public static void main(String[] args)
{
int choice = 0;
while(choice != 4)
{
int size;
Scanner sizeScanner = new Scanner(System.in);
/* In the grades array, I get an error telling me that the local variable has not
yet been initialized. I want to initialize it using the scanner inside the if
statement*/
int[] grades = new int[size];
System.out.println("-----MENU-----");
System.out.println("1) Enter size");
System.out.println("2) Enter grades");
System.out.println("3) Calculate average");
System.out.println("4) Exit program.");
Scanner choiceScanner = new Scanner(System.in);
choice = choiceScanner.nextInt();
if(choice == 1)
{
System.out.println("Enter size");
sizeScanner = new Scanner(System.in);
size = sizeScanner.nextInt();
}
if(choice == 2)
{
/*If i initialize size = 0, and then try the print statement
below, it will print out a 0 instead of whatever is read
into it via the scanner. */
System.out.println(size)
System.out.println("Enter grades: ");
Scanner gradeScanner = new Scanner(System.in);
for(int i = 0; i < size; i++) //I get the same error here in my for loop.
{
grades[i] = gradeScanner.nextInt();
}
}
}
}
}
我正在尝试在第一个“if”语句中初始化变量“size”。如果我在那里初始化变量,它不会改变大小的实际值。我知道它超出了范围,但我不知道如何让它存储在那里。这也给我的成绩数组带来了问题,因为我需要知道“size”的大小来设置数组的大小。我得到的错误是:局部变量大小可能尚未初始化 Java(536870963)
答: 暂无答案
评论
int size = -1;
-1
size
System.in
System.in
Scanner
Scanner