4

我正在尝试自学 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);
}
}
4

1 回答 1

1

首先,您似乎并不真的需要 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);
}

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

于 2012-10-20T19:23:10.530 回答