gpt4 book ai didi

java - 彩票 - 猜正确的数字

转载 作者:行者123 更新时间:2023-12-01 17:16:33 25 4
gpt4 key购买 nike

Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.print("Enter a number u wish(1-1000): ");
int unos = input.nextInt();
int rand = random.nextInt(1000) + 1;
System.out.println(rand);
if (unos = random) {
System.out.printf("Congratz u won");
}
while (unos < rand) {
System.out.println("Your number is lower \t Try again: ");
unos = input.nextInt();
}
while (unos > rand) {
System.out.println("Your number is higher\t Try again: ");
unos = input.nextInt();
}

因此,如果我击中的数字不等于随机生成的数字,它会起作用,但一旦我击中,它就不会输出“Congratz u won”。它就这样终止了。为什么?

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

public class Lutrija {

public static void main(String []args){
Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.print("Uneti broj koji mislite da ce ispasti(1-1000): ");
int unos=input.nextInt();
int rand =random.nextInt(1000)+1;
System.out.println(rand);
while (unos!=rand){
if(unos==rand){
System.out.println("Congratz");
}
else if (unos>rand){
System.out.println("broj je veci od izvucenog");
unos=input.nextInt();
}
else if (unos<rand){
System.out.println("broj je manji od izvucenog");
unos=input.nextInt();
}
}
}
}

这不起作用,为什么?

最佳答案

您在 if 语句中使用赋值 = 而不是相等测试 ==。更改为:

while ((unos = input.nextInt()) != rand) {
// Tell them higher of lower
// No need to call input.nextInt() in loop body as it is called
// when reevaluating while condition
}
// Congratulate them since to get here, unos == rand

您还应该将代码包含在一个循环中,该循环将循环直到猜测等于随机数,否则它就会终止,因为任何 while 条件都不成立。

关于java - 彩票 - 猜正确的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21717082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com