好的,所以我的计算机老师要求我们做一个简单的游戏,要求用户猜测随机生成的数字,但是我想更进一步,使之能够在用户尝试某些操作时显示错误消息。这里的问题是,我是布尔语言的新手,而且,在使用java.util.Scanner和布尔值时遇到了一些麻烦。因此,如果有人可以快速浏览一下,我将不胜感激。

import java.util.Scanner;
import java.util.Random;

public class MoreGuessing{
//Instantiation
            Scanner reader = new Scanner(System.in);
            Random number = new Random();
//Variables
    int randomnumber = number.nextInt(10) + 1;
    int cntr = 1;
    static String decimalguessed;
    String error1 = "Error001: Decimal found, please enter a whole number between 1-10." + "\n" + "Program terminated......";//Decimal portion error.
    String error2 = "Please enter a positive number." + "\n" + "Program terminated......"; //Negative number error.
    String error3 = "Unknown character entered." + "\n" + "Program terminated......"; //Unknown character error.
//Verifier
public static boolean verifyLetters() {
    if (decimalguessed.matches("[a-zA-Z]+")){
        return true;
    }else{
        return false;
    }
}
public static void main(String [] args){
//Input and display
    System.out.print("Please enter a whole number between 1-10: ");
        decimalguessed = reader.nextLine();
//Process and Errors
while (decimalguessed != randomnumber) {
if (verifyLetters() != false){
            System.out.println(error3);
            System.exit(1);}
if (decimalguessed % 1 != 0) {
            System.out.println(error1);
            System.exit(1);}
if (decimalguessed < 0) {
            System.out.println(error2);
            System.exit(1);}
if (randomnumber != decimalguessed){
            System.out.println("You've lost, please make another attempt.");}
System.out.print("Please enter a whole number between 1-10: ");
    decimalguessed = reader.nextDouble();

cntr++;

    }
if (cntr == 1) {System.out.println("Congratulations! You've guessed the number on your first attempt!");;
}
else {System.out.println("Congratulations! You've guessed the number, it took you " + cntr + " tries");}
}
}

最佳答案

您需要分析您的输入。 decimalguessed是一个字符串,因此您不能像decimalguessed % 1这样进行比较。

您可以将其转换为整数,如下所示:

int guess = 0;
try {
    guess = Integer.parseInt(decimalguessed);
} catch (NumberFormatException e) {
    System.out.println("Your guess was not an integer: " + e.getMessage());
    System.exit(1);
}


这将处理decimalguessed包含字母和十进制小数点/分数的两种情况。 decimalguessed仍然是字符串,但是guess现在包含它的整数版本,因此您可以将其与randomnumber正确比较。 (您的循环之前不会退出,因为字符串永远不会==整数)



其他注意事项:

您不应该拥有:

if (condition) {
    return true;
} else {
    return false;
}


可以随时将其替换为

return condition;

09-06 02:16