基本上,test2、test3 等都在一个范围内声明,但在该范围关闭后,它们不再可用。作为修复(根据您要执行的操作来判断),我建议在方法的开头声明它们:=在方法的开头声明整数:
public static void main(String str[])
throws IOException
{
int test1 = -1, test2 = -1, test3 = -1, test4 = -1, test5 = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter up to 5 Tests:");
test1 = scan.nextInt();
if(test1 > -1)
{
test2 = scan.nextInt();
}
else
{
if(test2 > -1)
{
test3 = scan.nextInt();
}
else
{
if(test3 > -1)
{
test4 = scan.nextInt();
}
else
{
if(test4 > -1)
{
test5 = scan.nextInt();
}
}
}
}
}
此外,您的方法看起来不像您想要的那样;如果test1
是有效的,它接受 test2,但在那里完成。为此,您可能想要做的是:
public static void main(String str[])
throws IOException
{
int test1 = -1, test2 = -1, test3 = -1, test4 = -1, test5 = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter up to 5 Tests:");
test1 = scan.nextInt();
if(test1 > -1)
{
test2 = scan.nextInt();
}
if(test2 > -1)
{
test3 = scan.nextInt();
}
if(test3 > -1)
{
test4 = scan.nextInt();
}
if(test4 > -1)
{
test5 = scan.nextInt();
}
// Work with the tests.
}