彩票 - 猜猜正确的号码

时间:2014-02-12 01:55:52

标签: java if-statement random

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();
            }
        }
    }
}

这不起作用,为什么?

1 个答案:

答案 0 :(得分:5)

您在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条件都不会成立。

相关问题