当前位置: 首页 > 知识库问答 >
问题:

Java代码不断返回“错误:不兼容的类型:Object不能转换为int”

冉德元
2023-03-14
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个答案

颛孙博易
2023-03-14

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

ArrayList guesses = new ArrayList();

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

Arraylists是通用的(ArrayList ),因为它们要求在其构造中指定一个对象,以便您知道ArrayList中有什么。

 类似资料: