Java - 代码不断返回'错误:不兼容的类型:对象无法转换为int'

时间:2017-02-03 01:21:54

标签: java arraylist

在我的代码中,我试图将数组列表的最后一个元素与随机数进行比较,但我不断收到错误“不兼容的类型:对象无法转换为int”。我似乎无法找到解决方案。有问题的问题发生在布尔类'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;
        }
    }
}

然后,代码将运行以下测试程序

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();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您没有正确初始化arraylist。变化

ArrayList guesses = new ArrayList();

ArrayList<Integer> guesses = new ArrayList<Integer>();

Arraylists是通用的(ArrayList<E>),因为它们需要在其构造中指定一个对象,以便您知道arraylist中的内容。