具有用户输入代码的随机数生成器无法正常工作

时间:2018-01-06 21:28:59

标签: java random

我的另一个初学者问题。我提前道歉,但你能帮帮我吗?所以我想创建这个随机数生成器,它将生成数字1-100并要求用户输入。用户应该猜测,直到他最终获得​​正确的号码。最后,程序应该打印出你猜测的xx尝试"。所以问题是,当我测试代码时,两次运行正确,其他2次错误(尝试次数错误)。现在我也觉得代码可以用更好的方式编写,但不确切知道如何。谢谢

import java.util.Scanner;
import java.util.Random;
public class JavaApplication2018 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number, please");
        int attempt = input.nextInt();
        Random dice = new Random();
        int number;
        number = dice.nextInt(100) + 1;
        int counter = 0;
       while (number > attempt) 
       {
           System.out.println("I imagined a bigger number. Guess again!");
           attempt = input.nextInt();
           counter++;
       }

       while (number < attempt)
       {
           System.out.println("I imagined a smaller number. Guess again!");
           attempt = input.nextInt();
           counter++;
       }

       if (number == attempt)
       {

           counter++;
       }


       System.out.println("You guessed from " + counter +". attempt" );

    }  


}

3 个答案:

答案 0 :(得分:1)

用户猜测一次,如果它大于随机数,那么它将再次迭代,如果不是,它将在第二次迭代时,如果猜测再次大于该尝试,则不会好的,代码将以你想要的结果结束。

while (number > attempt || number<attempt) 
       {
        if(number>attempt){
           System.out.println("I imagined a bigger number. Guess again!");}             
        else
           System.out.println("I imagined a smaller number. Guess again!");

        attempt = input.nextInt();
        counter++;
       }
if (number == attempt)
   {

       counter++;
   }


   System.out.println("You guessed from " + counter +". attempt" );

}  

这段代码应该更好

答案 1 :(得分:1)

首先,您不需要两个while。你可以将它们放在一个while中,然后将if放在其中:

while(number ! attempt){
if(number > attempt)
...
else
...
}
System.out.println("good gusse" );

第二,我需要更多有关错误的详细信息才能帮助您解决问题

答案 2 :(得分:1)

用户引入第一个输入,然后进入无限循环,在该循环中将要求用户输入数字,直到最终猜到该值。此代码仅检查用户引入的值2倍最大值。如果它有帮助,请选择答案:D

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number, please");
    int attempt = input.nextInt();
    int number;
    number = new Random().nextInt(101);
    int counter = 1;

    while (true) {

        attempt = input.nextInt();
        counter++;


        if (number > attempt) {

            System.out.println("I imagined a bigger number. Guess again!");

        }else if (number < attempt) {

            System.out.println("I imagined a smaller number. Guess again!");

        }else {

            System.out.println("You guessed from " + counter + ". attempt");
            break;

        }


    }

}