Reputation: 49
I'm a beginner in Java. Can somebody please help me identify and fix the errors in the following code? Thanks!
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!" );
}
}
}
}
Upvotes: 0
Views: 166
Reputation: 997
You have defined Random instance within main method and trying to access from other method's body. Try to define the random instance outside the main method or pass the instance of random to toMultiply method as parameter
Upvotes: 0
Reputation: 11947
You can't access randomNumbers
because it is only local to the main
method. One thing you can do is move your randomNumbers
declaration and initialization outside the main method
and make it static so all methods in your class could access it. This would be known as creating a global variable.
Also, as a Java beginner, you should work on your naming conventions so you could avoid picking up on bad habits. Your class name appears to be very obscure. The name of your method/class/field should reflect what it represents/does.
Upvotes: 1