java - 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."
解决方案
取输入数字减去随机数的绝对值。
就像是:
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);
}
}
推荐阅读
- ios - Swift 4 数据读取选项
- c# - 如何在解决方案中使用特定版本的 nuget dll
- mongodb - 改变冲洗频率的风险
- java - Java return 做了奇怪的事情
- node.js - Socket io 不会在 phonegap 上连接
- python - DataTables - Python/Flask 中的服务器端处理 - 无法连接到服务器端脚本
- java - 使用 SPARK 从 zip 到 seq
- python - scikit -learn 管道 (SVC) 的特征重要性
- perforce - 如何找到之前提交的变更列表?
- apache-spark - Spark 应用程序无法在带有 YARN 的 EMR 上成功运行