首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >需要帮助重新创建一个带有while循环的猜谜游戏,以及使用java的其他循环

需要帮助重新创建一个带有while循环的猜谜游戏,以及使用java的其他循环
EN

Stack Overflow用户
提问于 2018-10-17 08:57:15
回答 2查看 49关注 0票数 -1

好的,我需要帮助完成一项我目前被困在学校的作业,我需要很多帮助。我试着这样做了几个小时,但仍然不知道如何做这项任务。下面是我的代码。

我在试着创造一个猜谜游戏。我被困住的是我应该如何循环10次猜测的次数,而不是更多。我试过了,它给了我一个无限循环。

我想要创造的是:

  • 从1到100中选择一个数字,玩家不知道这个数字是多少。
  • 玩家被要求猜测1到100中的一个数字。
  • 他们有10次机会猜测正确的数字。
  • 如果玩家在10次猜测中没有猜到正确的数字,则该玩家输掉了游戏。
  • 您让他们知道他们的猜测是太低还是太高,以帮助他们缩小猜测范围,最终在10次猜测用完之前猜到正确的数字。

导入java.util.Scanner;导入java.util.Random;公共类GuessGame3 { public static void (String[] args){ int num1;int count=0;int Guess=0;随机生成器=新随机();扫描仪扫描=新扫描器(System.in);//获取生成器num1 = generator.nextInt(100) + 1;while (Guess != num1){ System.out.println(“输入1到100之间的数字”);guess = scan.nextInt();count++;while (count > 10) System.out.println(“很抱歉你10次没猜到”+ count +“尝试”);if (Guess > num1) {System.out.println(“较低!”);} else if ( Guess < num1) {System.out.println(“较高”);} else System.out.println(“恭喜”+计数+“尝试次数”);}

EN

回答 2

Stack Overflow用户

发布于 2018-10-17 09:08:42

如果猜测是作为第一个while循环的一部分,而不是嵌套的,我建议进行检查:

while (count < 10){
System.out.println("Enter a number between 1 and 100");
            Guess = scan.nextInt();
count++;
     if ( Guess > num1)
    {
        System.out.println("Lower!");
    }
    else if (Guess < num1)
    {
        System.out.println("Higher");
    }
    else {
        break;
    }
}
if(count < 10) {
    System.out.println("Congrats! You have completed it in " + count + " tries!");
} else {
    System.out.println("Sorry you have run out of your 10 guesses!");
}

这里可能有一些错误,但您应该了解要点。

票数 0
EN

Stack Overflow用户

发布于 2018-10-17 09:27:58

问题出在循环中,按照您验证总尝试次数和猜测匹配的顺序。试试下面的

import java.util.Scanner;
import java.util.Random;
public class TestGame
{
  public static void main(String[] args)
  {
    int num1;
    int count = 0;
    int Guess = 0;
    int maxAllowedRetries = 10;

    Random generator = new Random();
    Scanner scan = new Scanner(System.in);

    //get generator
    num1 = generator.nextInt(100) + 1;
    while(count <= maxAllowedRetries)
    {
        if(count == maxAllowedRetries)
        {
            System.out.println("Sorry you have reached maximum number of retries!");
            break;
        }
        count++;
        System.out.println("Enter a number between 1 and 100");
        Guess = scan.nextInt();
        if(Guess == num1)
        {
            System.out.println("Great you got it Right!");
            break;
        }

        System.out.println("Sorry you didnt guess right. Its been " + count + " tries");

        if(Guess > num1)
        {
            System.out.println("Lower!");
        }
        else if(Guess < num1)
        {
            System.out.println("Higher");
        }
     }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52845884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档