Java货币面额问题

时间:2012-10-20 18:01:03

标签: java

我正在尝试自学Java并在我得到的书的两章中遇到一点点打扰:P这是其中一个练习中的一个:

“编写一个计算并显示输入的美元数量转换为货币面额的类别 - 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);
}
}

1 个答案:

答案 0 :(得分: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);
}

如果用户选择“是”,则无论如何都要完成主要方法,因此在这种情况下无需执行任何操作。