所以我参加了一个简介Java课程,到目前为止我很享受它。我有一个我正在上课的项目应该使用Java Diag框来请求用户输入来为视频游戏创建一个角色为角色生成健康和货币。
我已经完成了所有内容,除非生成字符运行状况时它应该停在两个小数位,但无论我做什么来调整我的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);
}
}
如果你们可以看看,任何帮助将不胜感激!
答案 0 :(得分:1)
您只是连接了一个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);
答案 1 :(得分:1)
在打印出double值的任何地方使用DecimalFormat,包括JOptionPane。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
IO.File.WriteAllText(IO.Path.GetTempPath & "storedText", TextBox1.Text)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click
MessageBox.Show(IO.File.ReadAllText(IO.Path.GetTempPath & "storedText"))
End Sub
答案 2 :(得分:1)
您的DecimalFormat并未在任何地方使用。你必须像
一样使用它df.format(startingCurrency)
获取自定义值。