java - 试图制作控制台应用程序猜谜游戏?我的逻辑正确吗?

标签 java

我的“If”语句没有给我写答案,例如,如果我输入“5”,它会打印得太高,这意味着随机数较低,但如果我输入一个较低的数字,如“4”,它也会打印low 这意味着随机数更高。它非常令人困惑,我只是想知道我在代码中的逻辑是否正确?

导入java.util.Scanner; 导入 java.lang.Math;

公开课GuessTest {

public static void main(String[] args) 
{
   System.out.println("Welcome to the gussing game, Try to guess the number am thinking of to win!");
   System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
   System.out.println();

    System.out.println("Am thinking of a number between 0 and 10. Try to guess it.");
    System.out.println();

   Scanner sc = new Scanner(System.in);
   String choice =  "y";

   while (!choice.equalsIgnoreCase("n"))
   {

     System.out.println("Enter the Number:");
       int guess = sc.nextInt();
       double rightNum = Math.random() *10;
       int randomNum = (int) rightNum;


       if (guess == randomNum)
       {
           System.out.println("Correct you've got it! The Number Was " + randomNum );
           System.out.println();
           System.out.println("Would you like to play again (y/n):");
           choice = sc.next();
       }
     else  if (guess < randomNum)
       {
           System.out.println("your too low!");
       }
     else if (guess > randomNum)
       {
            System.out.println("Your too high!");
       }   

}

}
}   

最佳答案

您在每次 while-loop 迭代中计算随机数。只需将计算代码移出循环即可计算一次:

double rightNum = Math.random() *10;
int randomNum = (int) rightNum;
while (!choice.equalsIgnoreCase("n")) {
    //your logic...
}

由于要进行多轮游戏,可以在接受新游戏时重新计算随机数:

double rightNum = Math.random() *10;
int randomNum = (int) rightNum;
while (!choice.equalsIgnoreCase("n")) {
    //your logic...
    if (guess == randomNum) {
        System.out.println("Correct you've got it! The Number Was " + randomNum );
        System.out.println();
        System.out.println("Would you like to play again (y/n):");
        choice = sc.nextLine();
        if (choice.equalsIgnoreCase("y")) {
            rightNum = Math.random() *10;
            randomNum = (int) rightNum;
        }
    }
    //your logic...
}

关于java - 试图制作控制台应用程序猜谜游戏?我的逻辑正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14948730/

相关文章:

java - 为什么我的阵列不起作用?

java - Hibernate 是否支持 UNION ALL?

java - 如何为 MQTT 客户端设置超时?

java - 使用 Hibernate Criteria API 返回每组的第一行

java - 我在 JPanel 上显示 BufferedImage 和文本字段时遇到问题

java - 创建一个单独的线程来从java中的2路串行端口读取

java - 在JAVA客户端/服务器应用程序中,我应该在通信接口(interface)的哪一部分存储实例变量?

java - 检查JPA实体是否存在而不加载它

java - Spring路由因无效路由而出现404错误

java - 如何找到多维数组的值总和并替换未使用索引的值?