gpt4 book ai didi

java - 卡在java中的输出错误

转载 作者:行者123 更新时间:2023-11-29 04:32:13 27 4
gpt4 key购买 nike

我的 java 程序中出现输出错误。我的程序是一个简单的猜谜游戏,它从用户那里获取一个数字并创建一个随机数。然后它找到这些数字之间的差异并将其显示给用户。我是初学者,所以请提供简单的指导。谢谢。这是我的代码:

import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random_Number, user_Number, difference;
String random;

random_Number = 1 + (int)(Math.random() * 100);

user_Number = JOptionPane.showInputDialog(null,
"Please guess a number between 1 to 5." + "Please input your number",
"Guessing Game", JOptionPane.INFORMATION_MESSAGE);

difference = JOptionPane.showMessageDialog(null,
"The difference between my number and your number is " + user_Number - random_Number,
"Guessing Game", JOptionPane.INFORMATION_MESSAGE);

boolean valid = random_Number == user_Number;
JOptionPane.showMessageDialog(null,
"Does your number and my number match?" + "\n" + valid,
"Guessing Game", JOptionPane.INFORMATION_MESSAGE);
}
}

这是我得到的错误(我使用 jGrasp):

RandomGuessMatch.java:13: error: incompatible types: String cannot be converted to int
user_Number = JOptionPane.showInputDialog(null,

RandomGuessMatch.java:18: error: bad operand types for binary operator '-'
"The difference between my number and your number is " + user_Number - random_Number,

最佳答案

您可以尝试如下所示。此代码有效。

import javax.swing.JOptionPane;
public class RandomGuessMatch {
public static void main(String[] args) {
int random_Number, difference;
String user_Number;
String random;

random_Number = 1 + (int) (Math.random() * 100);
System.out.println(random_Number);

user_Number = JOptionPane.showInputDialog(null,
"Please guess a number between 1 to 5." + "Please input your number", "Guessing Game",
JOptionPane.INFORMATION_MESSAGE);

JOptionPane.showMessageDialog(null,
"The difference between my number and your number is "
+ (Integer.parseInt(user_Number) - random_Number),
"Guessing Game", JOptionPane.INFORMATION_MESSAGE);

boolean valid = (random_Number == Integer.parseInt(user_Number));
JOptionPane.showMessageDialog(null, "Does your number and my number match?" + "\n" + valid, "Guessing Game",
JOptionPane.INFORMATION_MESSAGE);
}
}

关于java - 卡在java中的输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43379141/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com