java - 不知道用户什么时候才能停止猜测呢?

标签 java arrays

write a program that makes the computer guess the number you are thinking of the computer will ask you to enter a number between 100 and 200 then will randomly try to guess ( using a Random number generator) . the program will keep track of how many times it takes for the computer to guess the number and will print out the number of guesses at the end.

这就是我所做的:

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

public class fianl {

   public static void main(String[] args)
   {

       Scanner keyboard=new Scanner(System.in);

       Random rdm=new Random();
       int guessnum=rdm.nextInt(70-20+1)+20;
       System.out.println("Guess the number between 100 and 200");
       int i=0,temp;

       do
       {
           temp=keyboard.nextInt();
           i++;
       }
       while(guessnum!=temp);
       System.out.println("user has taken "+i+" chances to guess:"+guessnum);
       keyboard.close();
   }
}

最佳答案

你的逻辑有问题。计算机只会猜测 20 到 70 之间的数字,但用户输入的是 100 到 200 之间的数字。此外,您正在猜测计算机的编号,而不是相反。我也清理了你的代码一点。

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

public class ComputerGuesser {

   public static void main(String[] args)
   {

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

       int computerGuess = 100 + random.nextInt(200-100+1);
       int guesses = 0;

       System.out.println("Enter a number from 100 to 200: ");
       int guess = Integer.parseInt(scan.nextLine());
       scan.close();

       while (computerGuess != guess)
       {       
           computerGuess = 100 + random.nextInt(200-100+1);
           guesses++;

           System.out.println("Guesses: " + guesses + ", Computer Guess: " + computerGuess + ", Your Guess: " + guess);
       }
   }
}

关于java - 不知道用户什么时候才能停止猜测呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158060/

相关文章:

Java的URL无法正确解析字符串

java - Spring引导maven插件: spring-boot:start shuts down the web app immediately (using jetty)

javascript - angularjs - 基于先前选择选项的嵌套 json 的 ng-options

iphone - 当Array更改时自动更新UITableView

javascript - 没有得到正确的结果

java - 按按钮关闭 Wicket 模式窗口

Java构造函数脚本

java - 如何通过 xsd 验证 org.w3.dom.Document?

javascript - 如何清空一个对象,它是javascript中数组的元素

javascript - 如何使用动态生成的文件名数组在 Grunt 中运行任务?