作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试自学 Java,但在我拿到的书的两章中遇到了一点小问题 :P 这是其中一个练习中的一个:
“编写一个类,计算并显示输入的美元数到货币面额的转换——20s、10s、5s 和 1s。”
到目前为止,我将进行四个小时的阅读,从 0 编码知识开始,希望这听起来不是一个简单到难以回答的问题。我确信有一种更有效的方式来编写整个内容,但我的问题是如果用户回答"is"我如何终止整个内容或者如果他们回答“否”则继续修改版本?
如果你们能给我任何关于学习 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);
}
}
最佳答案
首先,您似乎真的不需要 isYes 和 isNo 这两个 boolean 值。基本上,您询问用户是否需要不同的解决方案,即一个真/假值(或者更确切地说:isNo 与 !isYes 相同,因为选项 Pane 将仅返回值 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);
}
如果用户选择"is",您的主要方法无论如何都已完成,因此在这种情况下无需执行任何操作。
关于Java货币面额问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12991189/
我有一个像这样的对象: var currencyTypes = { NOK: {value:1.00000, name: "Norske kroner", denomination: "k
我是一名优秀的程序员,十分优秀!