首页 > 解决方案 > 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."

标签: java

解决方案


取输入数字减去随机数的绝对值。

就像是:

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

推荐阅读