2012-10-20 38 views
4

我想自學Java和運行成一個小嗝只是兩章進書我:P這是一個從演習之一:Java的貨幣面額發行

「寫一個類計算並顯示輸入的美元兌換成貨幣面值--- 20s,10s,5s和1s。「

我正在進行四個小時的閱讀,從0到目前爲止的編碼知識,所以希望這聽起來不是太簡單的問題要回答。我確信有一種更有效的方式來寫這整個事情,但我的問題涉及如果用戶回答「是」或者如果他們回答「否」時繼續使用修訂版本,我可以終止整個事情?

此外,任何建議或指導,你們可以給我學習Java的將不勝感激! 感謝您抽出寶貴的時間來閱讀這篇

import javax.swing.JOptionPane; 
public class Dollars 
{ 
    public static void main(String[] args) 
    { 
     String totalDollarsString; 
     int totalDollars; 
     totalDollarsString = JOptionPane.showInputDialog(null, "Enter amount to be  converted", "Denomination Conversion", JOptionPane.INFORMATION_MESSAGE); 
    totalDollars = Integer.parseInt(totalDollarsString); 
    int twenties = totalDollars/20; 
    int remainderTwenty = (totalDollars % 20); 
    int tens = remainderTwenty/10; 
    int remainderTen = (totalDollars % 10); 
    int fives = remainderTen/5; 
    int remainderFive = (totalDollars % 5); 
    int ones = remainderFive/1; 
    JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties + "\nTen Dollar Bills: " + tens + "\nFive Dollar Bills: " + fives + "\nOne Dollar Bills: " + ones); 
    int selection; 
    boolean isYes, isNo; 
    selection = JOptionPane.showConfirmDialog(null, 
     "Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); 
    isYes = (selection == JOptionPane.YES_OPTION); 
     JOptionPane.showMessageDialog(null, "You responded " + isYes + "\nThanks for your response!"); 
     isNo = (selection == JOptionPane.NO_OPTION); 
     int twenties2 = totalDollars/20; 
     int tens2 = totalDollars/10; 
     int fives2 = totalDollars/5; 
     int ones2 = totalDollars/1; 
     JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2); 
} 
} 

回答

0

首先,你並不真的似乎需要兩個布爾的isYes和ISNO。基本上你問用戶他是否想要一個不同的解決方案,即一個真/假值(或者說:isNo與!isYes相同,因爲選項窗格只會返回值YES_OPTION和NO_OPTION之一)。

你下一步想做什麼是去你的「精」 版本,如果用戶表示第一輸出是不是他想要的東西:

int selection = JOptionPane.showConfirmDialog(null, 
     "Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); 
if (selection == JOptionPane.NO_OPTION) {    
    int twenties2 = totalDollars/20; 
    int tens2 = totalDollars/10; 
    int fives2 = totalDollars/5; 
    int ones2 = totalDollars/1; 
    JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2); 
} 

如果用戶選擇「是」 ,無論如何你的主要方法都完成了,所以在這種情況下不需要做任何事情。

+0

感謝您的回覆!它幫助我完美地完成了這件事:D – user1761914