我正在写这个程序,让你输入每个季度,硬币,镍币和便士的金额,并以$ $返回金额。在那之后,我希望能够将他们生产的美元金额相加,而无需再次输入所有硬币金额。有任何想法吗?提前谢谢。
import java.util.*;
public class HalfDollar {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
quarterDollarAmount( );
dimeDollarAmount( );
nickelDollarAmount( );
pennyDollarAmount( );
totalDollarAmount( );
}
public static double quarterDollarAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterDollar = CONSOLE.nextInt( );
double amount = quarterDollar * 0.25;
System.out.println(quarterDollar + " Quarter are $" + amount);
return amount;
}
public static double dimeDollarAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeDollar = CONSOLE.nextInt( );
double amount = dimeDollar * 0.10;
System.out.println(dimeDollar + " Dimes are $" + amount);
return amount;
}
public static double nickelDollarAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelDollar = CONSOLE.nextInt( );
double amount = nickelDollar * 0.05;
System.out.println(nickelDollar + " Nickels are $" + amount);
return amount;
}
public static double pennyDollarAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyDollar = CONSOLE.nextInt( );
double amount = pennyDollar * 0.01;
System.out.println(pennyDollar + " Pennies are $" + amount);
return amount;
}
public static double totalDollarAmount( ) {
double quarter = quarterDollarAmount();
double dime = dimeDollarAmount();
double nickel = nickelDollarAmount();
double penny = pennyDollarAmount();
double total = quarter + dime + nickel + penny;
System.out.println("Total amount is $" + total);
return total;
}
}
答案 0 :(得分:1)
您没有对变量做任何事情。只是打电话给他们,然后他们就会超出范围。
您可以将返回的值存储在全局变量中以便以后使用。
private double quarter, dime, total;
public static void main(String[] args) {
quarter = quarterDollarAmount();
dime = dimeDollarAmount();
total = (quarter + dime);
s.o.p(total);
}
如果您在打印后不关心该值,您可以使用局部变量对其进行总计,或者按照以下方法总计您的方法。
public static void main(String[] args) {
s.o.p(quarterDollarAmount( ) + dimeDollarAmount( ) + ....);
}
要使您的值达到2位小数,请使用以下内容:
DecimalFormat format = new DecimalFormat("#.00");
Double total_formatted = Double.parseDouble(format.format(total));
s.o.p(total_formatted);
强制该值具有2个小数位,并且小数位左边有一个可选的位数。
最后,你可能不想让一切都变得静止。它基本上打败了面向对象的点,因为静态变量将持续存在于类的所有对象中。
答案 1 :(得分:1)
double total = 0.0;
total += quarterDollarAmount( );
total += dimeDollarAmount( );
total += nickelDollarAmount( );
total += pennyDollarAmount( );
totalDollarAmount( total );