i want to make a random number guessing game but i keep getting thrown this error "java: cannot find symbol
symbol: variable randNum
location: class Main". how can i resolve this?
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
makeRandNum();
readInput();
checkInput();
}
public static void makeRandNum() {
// creating number generator
Random randNumGen = new Random();
// generates the number
int randNum = randNumGen.nextInt(11);
System.out.println(randNum);
}
public static void readInput() {
//creates a new instance of the util scanner class
Scanner userInput = new Scanner(System.in);
// reads user input (int)
int guessedNum = userInput.nextInt();
}
public static void checkInput(){
if (guessedNum.equals(randNum)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
}
>Solution :
You are using randNum and guessedNum in checkInput() function but the variables are declared in makeRandNum() and readInput() function. To make the values accessible, make the return type of makeRandNum() and readInput() as int and then pass the returned value to the checkInput function as parameter.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int randNum = makeRandNum();
int guessedNum = readInput();
checkInput(randNum, guessedNum);
}
public static int makeRandNum() {
// creating number generator
Random randNumGen = new Random();
// generates the number
int randNum = randNumGen.nextInt(11);
System.out.println(randNum);
return randNum;
}
public static int readInput() {
// creates a new instance of the util scanner class
Scanner userInput = new Scanner(System.in);
// reads user input (int)
int guessedNum = userInput.nextInt();
return guessedNum;
}
public static void checkInput(int randNum, int guessedNum) {
if (guessedNum == randNum) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
}
and the output is as follows :
5
15
Incorrect