在我的代码中,我试图将数组列表的最后一个元素与一个随机数进行比较,但我一直收到错误提示“不兼容的类型:无法将对象转换为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();
}
}
}
ArrayList<Integer>
。 - Hovercraft Full Of Eels