我正在为CS课程开发这个程序,并希望用户输入每个硬币的金额,向他们显示所述金币数量的金额值,然后将每个输出的钱加起来。
到目前为止我所拥有的东西允许某人为每种类型的硬币输入一笔钱,并显示许多硬币的金额,但我似乎无法弄清楚如何添加所有的金钱价值在末尾。我需要一个单独的方法来调用每种方法返回的所有金额。任何帮助,将不胜感激!这是我到目前为止所做的:
import java.util.*;
public class Coins {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
quarterDollarAmount( );
dimeDollarAmount( );
nickelDollarAmount( );
pennyDollarAmount( );
}
public static void quarterDollarAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterAmount = CONSOLE.nextInt( );
double amount = quarterAmount * 0.25;
System.out.println(quarterAmount + " quarter are $" + amount);
}
public static void dimeDollarAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeAmount = CONSOLE.nextInt( );
double amount = dimeAmount * 0.1;
System.out.println(dimeAmount + " dimes are $" + amount);
}
public static void nickelDollarAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelAmount = CONSOLE.nextInt( );
double amount = nickelAmount * 0.05;
System.out.println(nickelAmount + " nickels are $" + amount);
}
public static void pennyDollarAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyAmount = CONSOLE.nextInt( );
double amount = pennyAmount * 0.01;
System.out.println(pennyAmount + " pennies are $" + amount);
}
}
好的,所以我用各自的硬币类型改变了所有的方法:
public static double pennyDollarAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyAmount = CONSOLE.nextInt( );
double amount = pennyAmount * 0.01;
System.out.println(pennyAmount + " pennies are $" + amount);
return amount;
}
并添加了方法:
public static double totalDollarAmount( ) {
double quarters = quarterDollarAmount();
double dimes = dimeDollarAmount();
double nickels = nickelDollarAmount();
double pennies = pennyDollarAmount();
int total = quarters + dimes + nickels + pennies;
System.out.println("Total amount is $" + total);
}
}
但是现在,编译器输出说(我出于显而易见的原因取出了我的系统详细信息):
1 error found:
File: /Users//Documents/Semester 2/CS/Coins.java [line: 51]
Error: /Users//Documents/Semester 2/CS/Coins.java:51: possible loss of precision
found : double
required: int
并将光标置于+ in + pennies之前;知道这意味着什么吗?
答案 0 :(得分:1)
您需要return amount;
并将所有与资金相关的功能的回复类型从void
更改为double
。
public static double quarterDollarAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterAmount = CONSOLE.nextInt( );
double amount = quarterAmount * 0.25;
System.out.println(quarterAmount + " quarter are $" + amount);
return amount;
}
然后在调用函数时捕获变量中的返回值。
double quarters = quarterDollarAmount();
...
double pennies = pennyDollarAmount();
然后,您可以将存储在这些变量中的值一起添加到您想要的结果中。
double total = quarters + ... + pennies;
答案 1 :(得分:0)
您可以设置global
变量并将计算结果设置为此variable
并添加所有变量。
或
将函数的返回类型从void
更改为double
并执行总和。
答案 2 :(得分:0)
你需要一个类变量
public static double totalAmount=0.0
将使用代码
在每个方法中更新 totalAmount += amount;
。
然后
public static void getTotalAmount() {
System.out.println(" Total Amount of coins are $" + totalAmount);
}
将完成这项工作。