gpt4 book ai didi

Java货币面额问题

转载 作者:搜寻专家 更新时间:2023-11-01 03:54:25 25 4
gpt4 key购买 nike

我正在尝试自学 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com