*4.26(金融应用:货币单位)重写程序清单2-10,解决将float型值转换为int型值时可能会造成精度损失的问题。读取的输入值是一个字符串,比如“11.56”。你的程序应该应用indexOf和substring方法提取小数点前的美元数量,以及小数点后的美分数量。

*4.26(Financial application: monetary units) Rewrite Listing 2.10, ComputeChange.java, to fix the possible loss of accuracy when converting a float value to an int value. Read the input as a string such as “11.56”. Your program should extract the dollar amount before the decimal point, and the cents after the decimal amount using the indexOf and substring methods.

下面是参考答案代码:

import java.util.*;

public class MonetaryUnitsQuestion26 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Receive the amount
System.out.print("Enter an amount in double, for example 11.56: ");
String amount = input.nextLine();

int remainingAmount = (int)(Integer.parseInt(amount.substring(0, amount.indexOf('.'))) * 100
+ Integer.parseInt(amount.substring(amount.indexOf('.')+1)));

// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;

// Display results
System.out.println("Your amount " + amount + " consists of");
System.out.println(" " + numberOfOneDollars + " dollars");
System.out.println(" " + numberOfQuarters + " quarters ");
System.out.println(" " + numberOfDimes + " dimes");
System.out.println(" " + numberOfNickels + " nickels");
System.out.println(" " + numberOfPennies + " pennies");

input.close();
}
}

运行效果:

第四章第二十六题(金融应用:货币单位)(Financial application: monetary units)_代码规范

注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等