mercredi 26 août 2015

math.random always give 0 result

I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I'm using Sublime Text. Here is the code

import java.util.Scanner;

public class RepeatAdditionQuiz{
    public static void main(String[] args){
        int number1 = (int)(Math.random()%10);
        int number2 = (int)(Math.random()%10);

        Scanner input = new Scanner(System.in);

        System.out.print(
            "What is "+number1+" + "+number2+"?");
        int answer = input.nextInt();

        while(number1+number2 != answer){
            System.out.print("Wrong answer. Try again. What is "
                 +number1+" + "+number2+"? ");
            answer = input.nextInt();
        }
        System.out.println("You got it!");
    }
}

But the problem is, when I compiled it and executed it. It gives me result

what is 0 + 0?_

every time. It suppose to give me random number, and yes, it can be 0. But I tried to run it more than 10 times, it keeps giving me 0 + 0, when it's suppose to random from 0-9.

The result of 0 + 0 is fine when I typed 0 as a result, it gets me out of the loop

Did I miss something to make the math library works? How can I fix the randomize issue?




Aucun commentaire:

Enregistrer un commentaire