程序清单
5-1 RepeatAdditionQuiz.java from page 138
代码完成任务:两位数相加的答案,循环直到用户输入正确为止
import java.util.*;
public class demo{
public static void main(String[] args) {
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
//0 create a Scanner
Scanner input = new Scanner(System.in);
//1 create the expression
System.out.print(
"what is " + number1 + " + " + number2 + " ? ");
int answer = input.nextInt();
//2 test the answer
while (number1 + number2 != answer) {
System.out.print("wrong answer.try again.what is "+ number1 + " + "+number2+" ? ");
answer = input.nextInt(); //input answer again
}
System.out.println("you got it");
}
}
5-2 & 5-3 GuessNumberOneTime.java from page 140、141
代码完成任务:产生0-100的随机数,用户猜测并给出提示
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 generate a random number to be guessed
int number = (int)(Math.random() * 101); //use 101
//1 create a Scanner and initiate
Scanner input = new Scanner(System.in);
System.out.println("guess a magic number between 0 and 100 "); //title
//2 guess the number
int guess = -1; //assume
//3 test
while(guess != number) {
System.out.println("enter your guess:");
guess = input.nextInt(); // input again then use if loop to test
if (guess == number)
System.out.println("yes,the number is " + number);
else if (guess > number)
System.out.println("your guess is too high");
else
System.out.println("your guess is too low");
}
}
}
5-4 SubtractionQuizLoop.java from page 142
代码完成任务:产生5道题目,报告正确个数,显示测试所花费时间,列出所有题目及回答情况。
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 initiate some constants and viarables,create a Scanner
final int NUMER_OF_QUESTIONS =5; //number of questions
int correctCount = 0; //count the number of correct answers
int count = 0; //count the number of questions
long startTime = System.currentTimeMillis();
String output = " "; //output string is initially empty
Scanner input = new Scanner(System.in);
while (count < NUMER_OF_QUESTIONS) {
//1 generate 2 random single-digit integers
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
//2 if number1 < number2,swap them
if (number1 < number2) {
number1 = number1 ^ number2;
number2 = number1 ^ number2;
number1 = number1 ^ number2; // a=a+b/use the third party get same result
}
//3 answer (number1 -number2)
System.out.println("what is " + number1 + " - " + number2 + " is ?");
int answer = input.nextInt();
// 4 grade the answer and display the result
if (answer == (number1 - number2)) {
System.out.println("correct,the answer is " + (number1 - number2));
correctCount++; //increase the correct count
}
else {
System.out.println(",the answer is not" + answer);
}
count++; //increase the count for ending the loop
//5 fill in the string output
output += "\n" + number1 + number2 + "=" + answer +
((number1 - number2 == answer) ? "correct" : "wrong");
}
//6 comput the time
long endTime = System.currentTimeMillis();
long testTime = startTime - endTime;
System.out.println("correct count is" + correctCount
+ "\ntest time is" + testTime / 1000 + "seconds\n" + output);
}
}
5-5 sentinelValue.java from page 144
代码完成任务:读取并计算不定整数之和,并用0结束循环。
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 create a Scanner
Scanner input = new Scanner(System.in);
//1 read an initial data
System.out.println("enter a integer:");
int data = input.nextInt();
//2 keep reading until the input is 0
int sum = 0;
while (data != 0){
sum+=data;
System.out.println("enter the next integer:");
data = input.nextInt(); //do not forget this input expression !
}
//3 display the result
System.out.println("the sum is " + sum);
}
}
5-6 TestDoWhile.java from page 147
代码完成任务:改变5-5的while结构
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 create a Scanner
Scanner input = new Scanner(System.in);
//1 read an initial data
System.out.println("enter a integer:");
int data = input.nextInt();
//2 keep reading until the input is 0
int sum = 0;
do{
sum+=data;
System.out.println("enter the next integer:");
data = input.nextInt(); //do not forget this input expression !
}while (data != 0);
//3 display the result
System.out.println("the sum is " + sum);
}
}
5-7 MultiplicationTable.java from page 153
代码完成任务:嵌套循环for打印乘法表。
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 diaplay the heading
System.out.println(" Multiplication Table");
//1 diaplay the number title
System.out.print(" "); //3 blanks
for(int j = 1 ; j <= 9 ; j++){
System.out.print(" " + j); // 3 blanks
}
System.out.println("\n---------------------------------");
//2 display the table body
for (int i = 1; i <= 9;i++){ // start the column
System.out.print(i + "| "); // create the lines' names, and do not new a line here
for (int j = 1;j <= 9;j++){
//3 display and align
System.out.printf("%4d", i * j);
}
System.out.println(); //newline
}
}
}
5-8 TestSum.java from page 155
代码完成任务:改变浮点数计算顺序,如何提高精度,结论为先加较小数再加较大数是减小误差的一种方法
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 initiate sum
double sum = 0;
double sum1 = 0;
double sum2 =0;
//1 add 0.01,0.02...1 to sum
for (double i = 0.01;i <= 1.0 ; i += 0.01){
sum += i;
} //the last i cannot be added to sum
//2 add 0.01...1.0 to sum by using the integer count
double countValue = 0.01;
for (double count = 0;count < 100;count++){
sum1 += countValue;
countValue += 0.01;
}
//3 add 0.01...1.0 to sum by using the integer count
double countValue1 = 1.0;
for (double count = 0;count < 100;count++){
sum2 += countValue1;
countValue1 -= 0.01;
}
//4 display the result
System.out.println("the sum using float count is " + sum);
System.out.println("the sum using integer count is " + sum1);
System.out.print("the sum using integer count & inverted oredr is " + sum2);
}
}
运行结果如下:
5-9 GreatestCommonDivisor.java from page 157(示例学习)
代码完成任务:选出最大公约数
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 create a Scanner
Scanner input = new Scanner(System.in);
//1 enter 2 integers
int number1 = input.nextInt();
int number2 = input.nextInt();
//2 pick out the gcd using loop
int gcd = 1;
int possibleGcd = 2;
while (possibleGcd <= number1 && possibleGcd <= number2 ){
if (number1 % possibleGcd == 0 && number2 % possibleGcd == 0)
gcd = possibleGcd;
possibleGcd++;
}
//3 display
System.out.println("the gcd is " + gcd);
}
}
5-10 FutureTuition.java from page 158(示例学习)
代码完成任务:循环结构下,指定金额的学费,按一定比率增加,多少年后学费翻倍。
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 initialize
double tuition = 10000;
int year = 0;
//1 loop
while (tuition < 20000) {
tuition = tuition * 1.07;
year ++;
}
//2 display
System.out.println("tuition will be doubled in " + year +" years.");
System.out.printf("tuition will be $ % .2f in %1d years",tuition,year);
}
}
5-11 Dec2Hex.java from page 159(示例学习)
代码完成任务:将10进制转换成16进制
import java.util.*;
public class demo{
public static void main(String[] args) {
//0 create a Scanner
Scanner input = new Scanner(System.in);
// 1 enter a decimal integer
System.out.println("enter a decimal integer:");
int decimal = input.nextInt();
//2 convert hex to dec
String hex = "";
while (decimal != 0) {
int hexValue = decimal % 16;
//3 convert a decimal value to hex digit
char hexDigit = (0 <= hexValue && hexValue <= 9)?
(char)(hexValue+'0'):(char)(hexValue-10+'A');
hex = hexDigit + hex;
decimal = decimal / 16;
}
//4 display
System.out.println("the hex number is " + hex);
}
}
5-12 TestBreak.java from page161
代码完成任务:测试break的作用
public class demo {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100) {
break; // condition is satified ,jump whole loop
}
}
System.out.println("the number is " + number); //14
System.out.println("the sum is " + sum); //105
}
}
5-13 TestContinue.java from page 161
代码完成任务:测试continue的作用
public class demo {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue; //jump out of the "if" structure
sum += number;
}
System.out.println("the number is " + number);//189
System.out.println("the sum is " + sum); //20
}
}
5-14 Palindrome.java from page 163(示例学习)
代码完成任务:判断一个字符串是否是回文
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
// 0 create a Scanner
Scanner input = new Scanner(System.in);
// 1 enter a string
System.out.println("plz enetr a string:");
String s = input.nextLine();
//2 the index of the first character in the string
int low =0;
// 3 the index of the last character in the string
int high = s.length()-1;
//4 assume the string is palindrome
boolean isPalinfrome = true;
//5 judge
while (low < high){
if (s.charAt(low) != s.charAt(high)){
isPalinfrome = false;
break;
}
low++;
high--;
}
//6 display
if (isPalinfrome){
System.out.println(s + " is a palindrome");
}
else{
System.out.println(s + " is not a palindrome");
}
}
}
5-15 PrimeNumber.java from page 165(示例学习)
代码完成任务:判断是否是素数,统计素数个数并打印前50个素数,每行10个
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
//0 initiate
final int NUMBER_OF_PRIMES = 50;// number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 10;//display 10 per line
int count = 0;//count the number of prime numbers
int number = 2;//a number to be tested for primeness
System.out.println("the first 50 prime numbers are \n");
//1 repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES) {
// assume the number is prime
boolean isPrime = true;
//2 test whether number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { //if true , number is not prime
isPrime = false; //set isPrime to false
break; //exit the for loop
}
}
//3 display the prime number and increase the count
if (isPrime) {
count++;
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
System.out.println(number);
} else {
System.out.print(number + " ");
}
}
//4 check if the next number is prime
number++;
}
}
}