2.7 练习题
(1) 要购买物品的价格单位是美元和分。用现金付款,向营业员交付d美元c美分。用一个方法计算找零。请为该方法编写一个规范。要包含作用描述、初始条件、结束条件和参数描述。
(2) 日期包含月、日和年。一般将这些项表示为整数。例如July 4, 1776,其中,月为7,日为4,年为1776。
a. 有一个方法,将任何指定日期后推一天。为该方法编写规范。包含作用描述、初始条件、结束条件和参数描述。
b. 编写该方法的Java实现代码。设计和指定需要的其他方法。有人将在未来维护实现代码,因此,要包含注释,便于他们理解。
(3) 考虑下列方法,它交互地读写雇员组中各个雇员的身份证号、年龄、工资(以千美元计)和姓名。如何完善该程序?有的问题比较明显,有的则较为隐藏。请参照本章讨论的所有主题。
public static void main(String args[]) {
int x1, x2, x3, i;
String name;
X1 = input.nextInt();
x2 = input.nextInt();
x3 = input.nextInt();
while (x1 != 0) {
name = input.next ();
System.out.println(xl +"" + x2 + " " + x3 + name);
X1 = input.nextInt();
x2 = input.nextInt();
x3 = input.nextInt();
} // end while
} // end main
(4) 下面的代码有什么问题?
num = 50;
while(num >= 0)
{
System.out.println(num);
num=num+1;
}
(5) 在2.2.5节的银行示例中添加一个Transaction类,这个类跟踪交易的日期、时间、金额和类型(支票或存款)。
(6) 要尽可能为程序添加防故障检查,本章强调了它的重要性。在使用下列方法时,将出现什么错误?如何防止?
public static double computation(double x){
return java.lang.Math.sqrt(x)/java.lang.Math.cos(x);
} //end computation
(7) 2.3.4一节介绍过factorial方法,试为该方法编写循环不变式。
(8) 写出下述程序的循环不变式。
int i=20;
while(i>1)
i--;
(9) 在下面的代码中,假设数组项用随机整数值进行了初始化。写出下述程序的循环不变式。
int index = 0;
while(index < item.length)
if(item[index] > 0) {
sum += item[index];
} //end if
++ index;
} //end while
(10) 用for循环编写一个程序,对于任意大于0、且小于或等于给定n的整数,显示它的平方。
(11) 编写自我测试题(2)描述的方法,并声明循环不变式。
(12) 用循环不变式说明自我测试题(1)中的算法能够正确计算item[0]+ item[1]+…+item[n]。
(13) 下列代码旨在计算输入值x的平方根的floor(数字n的floor指小于等于n的最大整数)。
// Computes and writes floor(sqrt(x)) for
// an input value x >= 0.
public static void main(String args[]) {
int x; // input value
Scanner input = new Scanner(System.in);
// initialize
int result = 0; // will equal floor of sqrt(x)
int temp1= 1;
int temp2 = 1;
// read input
x = input.nextInt();
// compute floor
while (temp1< x) {
++result;
temp2 += 2;
temp1 += temp2;
} // end while
System.out.println("The floor of the square root of"
+ x +" is "+ result);
} // end main
该程序包含一个错误。
a. 当x=64时,程序生成什么输出?
b. 运行程序,消除错误。描述查找错误的步骤。
c. 如何使程序更加友好和防故障?
(14) 假设因一些致命错误,需要从嵌套的方法调用、while循环和if语句内部一个很深的位置异常终止程序。编写一个可从程序任何位置调用的诊断方法。该方法应将错误代码作为参数,显示相应的错误消息,并终止程序执行。







