2017-08-27 68 views
0

所以我正在介紹Java類,到目前爲止我很享受它。我有一個針對我正在工作的班級的項目,應該使用Java 診斷框來請求用戶輸入爲電子遊戲創建角色並生成角色的健康和貨幣。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); 
    } 
} 

如果你們可以看看,任何幫助將不勝感激!

+0

無論您輸出double值(包括JOptionPane),都可以使用DecimalFormat。 –

+1

您創建了'df',但您沒有在任何地方使用它。 – Gendarme

回答

1

你只是連接了一個double值而沒有格式化爲字符串。嘗試如下方法String.format():無論你打印出來的雙重價值,包括JOptionPane的

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

使用DecimalFormat的。

JOptionPane.showMessageDialog(null, "Your name is " + charName + " your starting health is " 
      + startingHealth + " your starting currency is " 
      + df.format(startingCurrency), // add this! 
      "Your character stats", 
      JOptionPane.INFORMATION_MESSAGE); 
1

您的DecimalFormat不會在任何地方使用。你必須使用它像

df.format(startingCurrency) 

獲得定製值。