user3299707
user3299707

Reputation: 1

Lottery - guess correct number

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

So, if I hit numbers that aren't equal to the randomly generated number it works, but once I hit, it doesn't output "Congratz u won". It just terminates. Why?

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

This doesn't work, why?

Upvotes: 0

Views: 302

Answers (1)

xlm
xlm

Reputation: 7594

You are using assignment = instead of equality test == in your if statement. Change to:

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

You also should embody your code in a single loop that loops until guess equals the random number otherwise it just terminates as none of the while conditions will hold.

Upvotes: 5

Related Questions