gpt4 book ai didi

Java 作业格式化

转载 作者:行者123 更新时间:2023-12-01 20:15:20 24 4
gpt4 key购买 nike

所以我正在参加 Java 入门类(class),到目前为止我很享受它。我有一个我正在从事的类(class)的项目,该项目应该使用 Java 对话框来请求用户输入来为视频游戏创建一个角色,并且为角色生成生命值和货币。

我已经完成了所有工作,除了生成字符健康状况时,它应该停在小数点后两位,但无论我如何调整我的 DecimalFormat 代码,我都无法得到它停在那里。

这是我的代码:

// This imports the GUI
import javax.swing.JOptionPane;
import java.text.*;

// This is the class declaration
public class CharacterGen
{
public static void main(String[] args)
{
// These are variable declarations
final double BASE_CURRENCY = 10.55;
final int BASE_HEALTH = 50;
int minHealthBonus = 1;
int maxHealthbonus = 5;

// This string dictates what is displayed
// in the input box title, the dialog box,
// and the type of dialog box
String charName;
charName = JOptionPane.showInputDialog(null,
"Enter your character's name",
"Welcome to Legendary Epics!",
JOptionPane.QUESTION_MESSAGE);

int startingHealth = 50 + (int) (Math.random() * 5);
double startingCurrency = 10.55 - (double) (Math.random() * 1);
DecimalFormat df = new DecimalFormat("#.##");
System.out.printf("%.2s", startingCurrency);

JOptionPane.showMessageDialog(null,
"Your name is " + charName
+ " your starting health is " + startingHealth
+ " your starting currency is " + startingCurrency,
"Your character stats",
JOptionPane.INFORMATION_MESSAGE);
}
}

如果你们能看一下,我们将不胜感激!

最佳答案

您只是连接了一个 double 值,而没有将其格式化为字符串。尝试如下方法 String.format():

JOptionPane.showMessageDialog(null, "Your name is " + charName + " your starting health is " + startingHealth +
" your starting currency is " + String.format("%.2f", startingCurrency),
"Your character stats",
JOptionPane.INFORMATION_MESSAGE);

关于Java 作业格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45907298/

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