我是Java的初学者。有人可以帮我识别并修复以下代码中的错误吗?谢谢!
import java.util.Scanner;
import java.util.Random;
public class p6_35
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
Random randomNumbers = new Random();
toMultiply();
}
public static void toMultiply();
{
int number1 = randomNumbers.nextInt();
int number2 = randomNumbers.nextInt();
System.out.printf( "How much is %d times %d?\n", number1, number2 );
int answer = input.nextInt();
int corrAns = number1 * number2;
if( corrAns == answer )
{
System.out.print( "Very good!" );
}
while( corrAns == answer )
{
number1 = randomNumbers.nextInt();
number2 = randomNumbers.nextInt();
System.out.printf( "How much is %d times %d?\n", number1, number2 );
answer = input.nextInt();
corrAns = number1 * number2;
if( corrAns == answer )
{
System.out.print( "Very good!" );
}
}
while( corrAns != answer )
{
System.out.printf( "No. Please try again.");
answer = input.nextInt();
corrAns = number1 * number2;
if( corrAns == answer )
{
System.out.print( "Very good!" );
}
}
}
}
答案 0 :(得分:1)
您无法访问randomNumbers
,因为它只是main
方法的本地。您可以做的一件事是将randomNumbers
声明和初始化移到main method
之外,并将其设置为静态,以便您班级中的所有方法都可以访问它。这将被称为创建一个全局变量。
此外,作为Java初学者,您应该遵循命名约定,这样可以避免不良习惯。您的班级名称似乎非常模糊。您的方法/类/字段的名称应该反映它代表/做的内容。
答案 1 :(得分:0)
您已在main方法中定义了Random实例,并尝试从其他方法的主体访问。尝试在main方法之外定义随机实例,或者将random实例作为参数
传递给toMultiply方法