Hoeins
Hoeins

Reputation: 49

How do I display a message that tells the user how far off their guess was from the randomly generated number?

Hello my task is to write a program that selects a random number between 1 and 5 and asks the user to guess the number. Then I must display a message that indicates the difference between the random number and the users guess. I then must display another message that displays the random number and the Boolean value true or false depending on whether the user's guess equals the random number. I have got the first part of the assignment done, where the user guesses a number and the computer generates a random number between 1 and 5, but I don't have a clue on how to make it display how close or far off they were or how to use a Boolean to show if the guess was equal to the number or not. I have left code of what I have so far. Thanks for the help and sorry if there is anything wrong with this post.

package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class RandomGuessMatch 
{

public static void main(String[] args) 
{
    int random = 1 + (int)(Math.random() * 5);

    Scanner input = new Scanner(System.in);
    JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
    JOptionPane.showMessageDialog(null,"The number is: " + random);
}

}

I need the first message to read something like "You were 3 numbers off." and the second message needs to read something like "You guessed the number 3 correctly" or "You did not guess the number 3 correctly."

Upvotes: 0

Views: 666

Answers (2)

Mano176
Mano176

Reputation: 176

Based on Zachary McGee's answer:

public static void main(String[] args)
{
    int random = 1 + (int)(Math.random() * 5);

    String input = JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
    if(Integer.parseInt(input) == random)
        JOptionPane.showMessageDialog(null, "You guessed correctly!");
    else
        JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - Integer.parseInt(input)) + " away");
    JOptionPane.showMessageDialog(null,"The number is: " + random);
}

If you have any questions to the code, feel free to ask :)

Upvotes: 0

Zachary McGee
Zachary McGee

Reputation: 504

Take the absolute value of the entered number subtracted by the random number.

Something like:

 package randomguessmatch;
    import java.util.Scanner;
    import javax.swing.JOptionPane;

    public class RandomGuessMatch 
    {

       public static void main(String[] args) 
       {
           int random = 1 + (int)(Math.random() * 5);

           Scanner input = new Scanner(System.in);
           JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
           JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - parseInt(input)) + " away");
           JOptionPane.showMessageDialog(null,"The number is: " + random);
        }
    }

Upvotes: 1

Related Questions