Java 同时循环直到随机滚动选定的数字,将随机放置在何处

Java 同时循环直到随机滚动选定的数字,将随机放置在何处,java,loops,random,while-loop,Java,Loops,Random,While Loop,在练习while循环时,我试着编写代码,在代码中输入随机数,然后猜测滚动需要多少次,但我不能在while中声明变量“chance”,但如果我将它放在前面,它只会滚动1次 Random rng = new Random(); Scanner input = new Scanner(System.in); System.out.println("Select a number you want to roll"); int choice = input.nextInt

在练习while循环时,我试着编写代码,在代码中输入随机数,然后猜测滚动需要多少次,但我不能在while中声明变量“chance”,但如果我将它放在前面,它只会滚动1次

    Random rng = new Random();
    Scanner input = new Scanner(System.in);
    System.out.println("Select a number you want to roll");
    int choice = input.nextInt();
    System.out.println("You feelin' lucky?\nHow many tries until you get " + choice);
    int tries = input.nextInt();
    int count = 0;
    int chance = rng.nextInt((100)+1);
        while (choice != chance) {
            System.out.println(chance);
            count++;

    }
    System.out.println("You won! It only took " + count + " tries.");
}

如何声明int chance以使其进入while循环?

您可以在while循环中将chance重新分配给一个新值:

int count = 0;
int chance = rng.nextInt((100)+1);
while (choice != chance) {
    System.out.println(chance);
    chance = rng.nextInt((100)+1);
    count++;
}
不要再次声明变量
chance
。只需将其重新分配给一个新值

chance = rng.nextInt((100)+1);
守则中的问题:

  • 循环从不使用
    尝试
  • 代码无法确定尝试次数不足以猜测的时间 用户输入的号码
  • 以下内容涉及这些问题:

    Random rng = new Random();
    Scanner input = new Scanner(System.in);
    System.out.println("Select a number you want to roll");
    int choice = input.nextInt();
    System.out.println("You feelin' lucky?\nHow many tries until you get " + choice);
    int tries = input.nextInt();
    int count = 1;
    int chance = rng.nextInt((100) + 1);
    
    while (tries > 0) {
        System.out.println(chance);
        if (choice == chance)
            break;
        chance = rng.nextInt((100) + 1);
        count++;
        tries--;
    }
    
    if (choice == chance) {
        System.out.println("You won! It only took " + count + " tries.");
    } else {
        System.out.println("You lost");
    }
    
    逻辑:

  • 使用
    尝试
    确定循环需要运行多少次。 每次运行后将其递减
  • 如果选择和机会相等,那么控制权就会跳出循环
  • 最后一个if条件是确定用户是否能够 在尝试次数内进行猜测

  • 如果我理解你的问题,我认为你应该使用
    do while
    循环。它将至少进入循环一次


    你需要在循环中重新分配机会。。。i、 e.
    chance=rng.nextInt(101)您知道它可能永远运行吗?
    
    Random rng = new Random();
    Scanner input = new Scanner(System.in);
    System.out.println("Select a number you want to roll");
    int choice = input.nextInt();
    System.out.println("You feelin' lucky?\nHow many tries until you get " + choice);
    int tries = input.nextInt();
    int count = 0;
    
    do {
       int chance = rng.nextInt((100)+1);
       System.out.println(chance);
       count++;
    } while (choice != chance)
    
    System.out.println("You won! It only took " + count + " tries.");