Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Can't get 2 different randoms

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can't get 2 different randoms

    Hi all.

    Making a simple maths game that takes a user input as an answer for the sum of two randomly generated numbers.

    Each time i run it, i get 7+7, 2+2, 3+3 etc, but never two different numbers.

    Any help would be much appreciated

    My code:

    import javax.swing.JOptionPane;
    public class Q3

    {
    public static void main (String [] args)
    {

    double first = Math.random()*10;
    int firstNumber = (int)first;
    double second = Math.random()*10;
    int secondNumber = (int)second;

    String userAnswerString = JOptionPane.showInputDialog("What is the sum of: " + firstNumber + "+" + secondNumber + " ?");
    double userAnswerDouble = Double.parseDouble(userAnswerString);
    int answer = (int)userAnswerDouble;

    if (answer == (firstNumber + secondNumber))
    {
    System.out.println("Congratulations! You are Correct!");
    }
    else
    {
    System.out.println("Sorry, that is wrong! The correct answer was: " + (firstNumber+secondNumber));
    }
    }
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Can't get 2 different randoms

    Please read the Announcement topic at the top of the sub-forum to learn how to post your code in code or highlight tags.

    I ran your code a couple times and always got two different numbers. Ensure you're running the latest version of your program. Delete all *.class files and recompile if you have to.

Similar Threads

  1. Question about Randoms and trying to use it
    By adipietro in forum Object Oriented Programming
    Replies: 9
    Last Post: September 29th, 2013, 04:37 PM