Reputation: 95
Inside my code, I am trying to compare the last element of an array list to a random number, but I keep getting the error "incompatible types: Object cannot be converted to int". I cannot seem to find a solution. The problem in question occurs at the boolean class 'checkLastGuess'.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
public class GuessingGame
{
int numToGuess = new Random().nextInt(10);
ArrayList guesses = new ArrayList();
void getGuess()
{
Scanner keyboard = new Scanner(System.in);
boolean valid = false;
int userGuess = 0;
while (valid == false)
{
System.out.print("What is your guess: ");
String num = keyboard.next();
char new_num = num.charAt(0);
if (Character.isDigit(new_num))
{
userGuess = Integer.parseInt(num);
if (userGuess >= 0 && userGuess < 10)
{
guesses.add(userGuess);
valid = true;
}
else
{
System.out.println("Invalid guess, please enter a number between 0 and 9.");
}
}
else
{
System.out.println("Invalid guess, please enter digit.");
}
}
}
void printGuesses() {
int list_length = guesses.size();
System.out.print("Your guesses: ");
for (int counter = 0; counter < list_length; counter++)
{
System.out.print(guesses.get(counter) + " ");
}
System.out.println();
}
boolean checkLastGuess()
{
int numToTest = guesses.get(guesses.size()-1);
if (numToTest == numToGuess)
{
return true;
}
else
{
return false;
}
}
}
The code is then ran through the following test program
public class GuessingGameTest {
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
System.out.println("Number to guess: " + game.numToGuess);
boolean guessedNumber = false;
while (!guessedNumber) {
game.getGuess();
guessedNumber = game.checkLastGuess();
}
}
}
Upvotes: 3
Views: 15367
Reputation: 8229
You're not initializing the arraylist correctly. Change
ArrayList guesses = new ArrayList();
to
ArrayList<Integer> guesses = new ArrayList<Integer>();
Arraylists are generic (ArrayList<E>
) in that they require an object to be specified in their construction so that you know what is in the arraylist.
Upvotes: 3