Java语言程序设计(基础篇)(原书第10版) 第七章编程练习题
程序员文章站
2024-03-02 12:04:58
...
心血来潮补一下之前没做完的课后题,争取全部做完,欢迎大家评论指正。
目录
- 7-1 指定等级
- 7-2 倒置输入的数
- 7-3 计算数字的出现次数
- 7-4 分析成绩
- 7-5 打印不同的数
- 7-6 修改程序清单5-15
- 7-7 统计一位数的个数
- 7-8 求数组的平均值
- 7-9 找出最小元素
- 7-10 找出最小元素的下标
- 7-11 统计学方面:计算标准差
- 7-12 倒置数组
- 7-13 随机数选择器
- 7-14 计算gcd
- 7-15 消除重复
- 7-16 执行时间
- 7-17 对学生排序
- 7-18 冒泡排序
- 7-19 是否排好序了?
- 7-20 修改选择排序法
- 7-21 游戏:豆机
- 7-22 游戏:八皇后
- 7-23 游戏:储物柜难题
- 7-24 仿真:优惠券收集人问题
- 7-25 代数问题:解二次方程式
- 7-26 完全相同的数组
- 7-27 相同的数组
- 7-28 数学方面:组合
- 7-29 游戏:选出四张牌
- 7-30 模式识别方面:四个连续相等的数
- 7-31 合并两个有序列表
- 7-32 划分列表
- 7-33 文化:中国生肖
- 7-34 对字符串中的字符排序
- 7-35 游戏:猜字游戏
需要书籍或者相关资料可以私聊!!!
7-1 指定等级
import java.util.Scanner;
public class Program7_1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int num = input.nextInt();
int[] stu = new int[num];
int best = 0;
System.out.printf("Enter %d scores: ", num);
for (int i = 0; i < num; i++) {
stu[i] = input.nextInt();
best = Math.max(best, stu[i]);
}
for (int i = 0; i < num; i++) {
System.out.printf("Student %d score is %d and grade is ", i, stu[i]);
if(stu[i] >= best - 10)
System.out.println('A');
else if(stu[i] >= best - 20)
System.out.println('B');
else if(stu[i] >= best - 30)
System.out.println('C');
else if(stu[i] >= best - 40)
System.out.println('D');
else
System.out.println('F');
}
input.close();
}
}
7-2 倒置输入的数
import java.util.Scanner;
public class Program7_2 {
public static void main(String[] args) {
System.out.print("Enter 10 integers: ");
Scanner input = new Scanner(System.in);
int[] num = new int[10];
for (int i = 0; i < 10; i++)
num[i] = input.nextInt();
for (int i = 9; i >= 0; i--)
System.out.print(num[i] + " ");
System.out.println();
input.close();
}
}
7-3 计算数字的出现次数
import java.util.Scanner;
public class Program7_3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[101];
int n;
System.out.print("Enter the integers between 1 and 100: ");
while(true) {
n = input.nextInt();
if(n == 0) break;
num[n]++;
}
for(int i = 1; i < 101; i++) {
if (num[i] != 0) {
System.out.print(i + " occurs " + num[i] + " time");
System.out.println(((num[i] > 1) ? 's' : ""));
}
}
input.close();
}
}
7-4 分析成绩
import java.util.Scanner;
public class Program7_4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] score = new double[101];
System.out.println("Enter several scores, ending with a negative number: ");
int cnt = 0;
int sum = 0;
int num = input.nextInt();
while(num >= 0){
score[num]++;
sum += num;
cnt++;
num = input.nextInt();
}
double average = 1.0 * sum / cnt;
int count1 = 0, count2 = 0;
for (int i = 0; i <= 100; i++) {
if(i >= average && score[i] != 0)
count1 += score[i];
else if(i < average && score[i] != 0)
count2 += score[i];
}
System.out.printf("The average is %.2f\n", average);
System.out.printf("%d score%s exceed the average score\n", count1, (count1 > 1) ? "s" : "");
System.out.printf("%d score%s below the average score\n", count2, (count2 > 1) ? "s" : "");
input.close();
}
}
7-5 打印不同的数
import java.util.Scanner;
public class Program7_5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int count = 0, m, flag;
System.out.print("Enter ten number: ");
for(int i = 0; i < 10; i++) {
flag = 0;
m = input.nextInt();
for(int j = 0; j < i; j++)
if(m == num[j]){
flag = 1;
break;
}
if(flag == 0) num[count++] = m;
}
System.out.println("The number of distinct number is " + count);
System.out.print("The distinct numbers are ");
for(int i = 0; i < count; i++) {
System.out.print(num[i]);
if(i < count-1) System.out.print(" ");
}
System.out.println();
input.close();
}
}
7-6 修改程序清单5-15
public class Program7_6 {
public static void main(String[] args) {
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");
int[] prime = new int[50];
// Repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES) {
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test if number is prime
for (int i = 0; prime[i] <= Math.sqrt(number) && i < count; i++) {
if(number % prime[i] == 0){
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
// Print the prime number and increase the count
if (isPrime) {
prime[count] = number;
count++;
}
// Check if the next number is prime
number++;
}
for (int i = 0; i < count; i++) {
System.out.print(prime[i] + " ");
if((i+1) % NUMBER_OF_PRIMES_PER_LINE == 0)
System.out.println();
}
}
}
7-7 统计一位数的个数
public class Program7_7 {
public static void main(String[] args) {
int[] count = new int[10];
for(int i = 1; i <= 100; i++) {
int m = (int)(Math.random() * 10);
System.out.print(m + " ");
if(i % 10 == 0) System.out.println();
count[m]++;
}
for(int i = 0; i < 10; i++)
System.out.println(i + " occurs " + count[i] + " times");
}
}
7-8 求数组的平均值
import java.util.Scanner;
public class Program7_8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 double numbers: ");
double[] num = new double[10];
for (int i = 0; i < 10; i++)
num[i] = input.nextDouble();
System.out.printf("The average of the array is: %.2f\n", average(num));
input.close();
}
public static int average(int[] array){
int sum = 0;
for (int i = 0; i < array.length; i++)
sum += array[i];
return sum / array.length;
}
public static double average(double[] array){
double sum = 0.0;
for (int i = 0; i < array.length; i++)
sum += array[i];
return 1.0 * sum / array.length;
}
}
7-9 找出最小元素
import java.util.Scanner;
public class Program7_9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] num = new double[10];
System.out.print("Enter ten numbers: ");
for(int i = 0; i < 10; i++)
num[i] = input.nextDouble();
System.out.println("The minimum number is: " + min(num));
input.close();
}
public static double min(double[] array) {
double min = array[0];
for(int i = 1; i < array.length; i++)
if(array[i] < min)
min = array[i];
return min;
}
}
7-10 找出最小元素的下标
import java.util.Scanner;
public class Program7_10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
double[] num = new double[10];
System.out.print("Enter ten numbers: ");
for(int i = 0; i < 10; i++)
num[i] = input.nextDouble();
System.out.println("The index of smallest element is: " + indexOfSmallestElement(num));
input.close();
}
public static int indexOfSmallestElement(double[] array) {
double min = array[0];
int indexMin = 0;
for(int i = 1; i < array.length; i++)
if(array[i] < min) {
min = array[i];
indexMin = i;
}
return indexMin;
}
}
7-11 统计学方面:计算标准差
import java.util.Scanner;
public class Program7_11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
double[] num = new double[10];
for (int i = 0; i < 10; i++)
num[i] = input.nextDouble();
System.out.printf("The mean is %.2f\n", mean(num));
System.out.printf("The standard deviation is %.5f\n", deviation(num));
input.close();
}
//Compute the deviation of an array of double values
public static double deviation(double[] x){
double sum = 0.0;
double average = mean(x);
for (int i = 0; i < 10; i++)
sum += (x[i] - average) * (x[i] - average);
return Math.sqrt(sum / 9);
}
//Compute the mean of an array of double values
public static double mean(double[] x){
double sum = 0.0;
for (int i = 0; i < 10; i++)
sum += x[i];
return sum / 10;
}
}
7-12 倒置数组
import java.util.Scanner;
public class Program7_12 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
int[] num = new int[10];
for (int i = 0; i < 10; i++)
num[i] = input.nextInt();
num = reverse(num);
for (int i = 0; i < 10; i++)
System.out.print(num[i] + " ");
System.out.println();
input.close();
}
public static int[] reverse(int[] list){
for (int i = 0; i < list.length / 2; i++) {
int temp = list[i];
list[i] = list[list.length - i - 1];
list[list.length - i - 1] = temp;
}
return list;
}
}
7-13 随机数选择器
public class Program7_13 {
public static void main(String[] args) {
System.out.println(getRandom(3,5,15,54));
}
public static int getRandom(int... numbers) {
int m, flag = 0;
while(true) {
m = (int)(Math.random() * 55);
for(int i = 0; i < numbers.length; i++)
if(m == numbers[i]) {
flag = 1;
break;
}
if(flag == 0) break;
}
return m;
}
}
7-14 计算gcd
import java.util.Scanner;
public class Program7_14 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter five numbers: ");
int[] num = new int[5];
for (int i = 0; i < 5; i++)
num[i] = input.nextInt();
System.out.println("The gcd of these five numbers is " + gcd(num));
input.close();
}
public static int gcd(int... numbers){
int gcd = numbers[0];
for (int i = 1; i < numbers.length; i++) {
int num = Math.min(gcd, numbers[i]);
for (int j = num; j >= 1; j--)
if(gcd % j == 0 && numbers[i] % j == 0){
gcd = j;
break;
}
}
return gcd;
}
}
7-15 消除重复
import java.util.Scanner;
public class Program7_15 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
int[] list = new int[10];
for (int i = 0; i < 10; i++)
list[i] = input.nextInt();
System.out.print("The distinct numbers are: ");
int[] ans = eliminateDuplicates(list);
for (int i = 0; i < ans.length; i++)
System.out.print(ans[i] + " ");
System.out.println();
input.close();
}
public static int[] eliminateDuplicates(int[] list){
int[] num = new int[list.length];
int count = 0;
for (int value : list) {
boolean flag = true;
for (int j = 0; j < count; j++)
if (value == num[j]) {
flag = false;
break;
}
if (flag) {
num[count] = value;
count++;
}
}
int[] ans = new int[count];
for (int i = 0; i < count; i++)
ans[i] = num[i];
return ans;
}
}
7-16 执行时间
import java.util.Arrays;
public class Program7_16 {
public static void main(String[] args) {
final int NUMBER = 100000;
int[] numbers = new int[NUMBER];
for (int i = 0; i < NUMBER; i++)
numbers[i] = (int) (Math.random() * (NUMBER + 1));
int key = (int) (Math.random() * (NUMBER + 1));
long startTime = System.currentTimeMillis();
System.out.println(linearSearch(numbers, key));
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("Execution time for linearSearch: " + executionTime);
Arrays.sort(numbers);
startTime = System.currentTimeMillis();
System.out.println(binarySearch(numbers, key));
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
System.out.println("Execution time for binarySearch: " + executionTime);
}
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++) {
if (key == list[i])
return i;
}
return -1;
}
/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return -low - 1; // Now high < low
}
}
7-17 对学生排序
import java.util.Scanner;
public class Program7_17 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int n = input.nextInt();
String[] name = new String[n];
double[] score = new double[n];
System.out.println("Please enter the name and score of the students:");
for(int i = 0; i < n; i++) {
name[i] = input.next();
score[i] = input.nextDouble();
}
scoreSort(name, score);
System.out.println("name\t score\t");
System.out.println("----------------");
for(int i = 0; i < n; i++)
System.out.printf("%-9s%-5.1f\n",name[i],score[i]);
input.close();
}
public static void scoreSort(String[] name, double[] score) {
String tempName;
double tempScore;
int k;
for(int i = 0; i < score.length-1; i++) {
k = i;
for(int j = i+1; j < score.length; j++)
if(score[j] > score[k])
k = j;
tempName = name[k]; name[k] = name[i]; name[i] = tempName;
tempScore = score[k]; score[k] = score[i]; score[i] = tempScore;
}
}
}
7-18 冒泡排序
import java.util.Scanner;
public class Program7_18 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] num = new double[10];
System.out.print("Please enter ten numbers: ");
for (int i = 0; i < num.length; i++)
num[i] = input.nextDouble();
bubbleSort(num);
for (int i = 0; i < num.length; i++) {
System.out.print(num[i]);
if (i < num.length - 1) System.out.print(" ");
}
System.out.println();
input.close();
}
public static void bubbleSort(double[] array) {
double temp;
for (int i = 0; i < array.length - 1; i++)
for (int j = 0; j < array.length - 1 - i; j++)
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
7-19 是否排好序了?
import java.util.Scanner;
public class Program7_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter list: ");
int n = input.nextInt();
int[] list = new int[n];
for (int i = 0; i < n; i++)
list[i] = input.nextInt();
if(isSorted(list))
System.out.println("The list is already sorted");
else
System.out.println("The list is not sorted");
}
public static boolean isSorted(int[] list){
for (int i = 1; i < list.length; i++) {
if(list[i] < list[i-1])
return false;
}
return true;
}
}
7-20 修改选择排序法
import java.util.Scanner;
public class Program7_20 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
double[] list = new double[10];
for(int i = 0; i < 10; i++)
list[i] = input.nextDouble();
selectionSort(list);
for (int i = 0; i < 10; i++)
System.out.print(list[i] + " ");
System.out.println();
input.close();
}
/** The method for sorting the numbers */
public static void selectionSort(double[] list) {
for (int i = list.length - 1; i > 0; i--) {
double currentMax = list[i];
int currentMaxIndex = i;
for (int j = i-1; j >= 0; j--) {
if (currentMax < list[j]) {
currentMax = list[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
list[currentMaxIndex] = list[i];
list[i] = currentMax;
}
}
}
}
7-21 游戏:豆机
import java.util.Scanner;
public class Program7_21 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of balls to drop: ");
int balls = input.nextInt();
System.out.print("Enter the number of slots in the bean machine: ");
int slot = input.nextInt();
int[] slots = new int[slot];
int maxBalls = 0;
System.out.println();
for(int i = 0; i < balls; i++){
int count = 0;
for (int j = 0; j < slot-1; j++) {
int num = (int) (Math.random() * 2);
if(num == 0)
System.out.print('L');
else {
System.out.print('R');
count++;
}
}
System.out.println();
slots[count]++;
maxBalls = Math.max(maxBalls, slots[count]);
}
System.out.println();
for (int i = maxBalls; i >= 1; i--) {
for (int j = 0; j < slot; j++) {
if(slots[j] >= i)
System.out.print("0");
else
System.out.print(" ");
}
System.out.println();
}
}
}
7-22 游戏:八皇后
public class Program7_22 {
public static void main(String[] args) {
int[] queen = new int[8];
for (int i = 0; i < 8; i++)
queen[i] = -1;
queen[0] = 0;
int row = 1;
while (row >= 0 && row < 8) {
boolean flag = false;
for (int i = queen[row] + 1; i < 8; i++)
if (check(row, i, queen)) {
flag = true;
queen[row] = i;
break;
}
if (queen[row] != -1 && flag)
row++;
else{
queen[row] = -1;
row--;
}
}
for(int i = 0; i < 8; i++){
for(int j = 0; j < queen[i]; j++)
System.out.print("| ");
System.out.print("|Q|");
for(int j = queen[i]+1; j < 8; j++)
System.out.print(" |");
System.out.println();
}
}
public static boolean check(int row, int col, int[] queen) {
for (int i = 0; i < row; i++)
if (queen[i] == col)
return false;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
if (queen[i] == j)
return false;
for (int i = row - 1, j = col + 1; i >= 0 && j < 8; i--, j++)
if (queen[i] == j)
return false;
return true;
}
}
7-23 游戏:储物柜难题
public class Program7_23 {
public static void main(String[] args) {
boolean[] lockers = new boolean[101];
for (int i = 1; i <= 100; i++)
lockers[i] = false;
for(int i = 1; i <= 100; i++){
for(int j = i; j <= 100; j += i)
lockers[j] = !lockers[j];
}
System.out.println("Opened lockers: ");
for(int i = 1; i <= 100; i++)
if(lockers[i])
System.out.print(i + " ");
}
}
7-24 仿真:优惠券收集人问题
public class Program7_24 {
public static void main(String[] args) {
String[] suit = {"Spade", "Heart", "Diamond", "Club"};
boolean[] check = new boolean[4];
for (int i = 0; i < 4; i++)
check[i] = false;
int count = 0;
while (!(check[0] && check[1] && check[2] && check[3]))
count += checkPoker(check, suit);
System.out.println("Numbers of picks: " + count);
}
public static int checkPoker(boolean[] check, String[] suit){
String[] card = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
int[] poker = new int[52];
for (int i = 0; i < 52; i++)
poker[i] = i;
for(int i = poker.length-1; i > 0; i--){
int j = (int) (Math.random() * (i+1));
int temp = poker[i];
poker[i] = poker[j];
poker[j] = temp;
}
int cnt = 0;
while (true){
cnt++;
int n = (int) (Math.random() * 52);
int color = n % 4, num = n % 13;
if(!check[color]){
check[color] = true;
System.out.printf("%s of %s\n", card[num], suit[color]);
break;
}
}
return cnt;
}
}
7-25 代数问题:解二次方程式
import java.util.Scanner;
public class Program7_25 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] eqn = new double[3];
double[] roots = new double[2];
System.out.print("Enter a, b, c: ");
for (int i = 0; i < 3; i++)
eqn[i] = input.nextDouble();
int num = solveQuadratic(eqn, roots);
System.out.println("Number of roots: " + num);
for (int i = 0; i < num; i++)
System.out.print(roots[i] + " ");
System.out.println();
input.close();
}
public static int solveQuadratic(double[] eqn, double[] roots){
double a = eqn[0], b = eqn[1], c = eqn[2];
double m = b*b - 4*a*c;
double n = -b / (2*a);
int num = 0;
if(m < 0)
num = 0;
else if(m == 0) {
roots[0] = n;
num = 1;
}
else {
roots[0] = n + Math.pow(m, 0.5) / (2 * a);
roots[1] = n - Math.pow(m, 0.5) / (2 * a);
num = 2;
}
return num;
}
}
7-26 完全相同的数组
import java.util.Scanner;
public class Program7_26 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter list1: ");
int n1 = input.nextInt();
double[] list1 = new double[n1];
for(int i = 0; i < n1; i++)
list1[i] = input.nextDouble();
System.out.print("Enter list2: ");
int n2 = input.nextInt();
double[] list2 = new double[n2];
for(int i = 0; i < n2; i++)
list2[i] = input.nextDouble();
if(equals(list1, list2))
System.out.println("Two lists are strictly identical");
else
System.out.println("Two lists are not strictly identical");
input.close();
}
public static boolean equals(double[] list1, double[] list2) {
if(list1.length != list2.length)
return false;
for(int i = 0; i < list1.length; i++)
if(list1[i] != list2[i])
return false;
return true;
}
}
7-27 相同的数组
import java.util.Scanner;
public class Program7_27 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter list1: ");
int n1 = input.nextInt();
int[] list1 = new int[n1];
for(int i = 0; i < n1; i++)
list1[i] = input.nextInt();
System.out.print("Enter list2: ");
int n2 = input.nextInt();
int[] list2 = new int[n2];
for(int i = 0; i < n2; i++)
list2[i] = input.nextInt();
if(equals(list1, list2))
System.out.println("Two lists are identical");
else
System.out.println("Two lists are not identical");
}
public static boolean equals(int[] list1, int[] list2) {
java.util.Arrays.parallelSort(list1);
java.util.Arrays.parallelSort(list2);
if(list1.length != list2.length)
return false;
for(int i = 0; i < list1.length; i++)
if(list1[i] != list2[i])
return false;
return true;
}
}
7-28 数学方面:组合
import java.util.Scanner;
public class Program7_28 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < 10; i++)
numbers[i] = input.nextInt();
for (int i = 0; i < 10; i++)
for (int j = i+1; j < 10; j++)
System.out.printf("(%d, %d)\n", numbers[i], numbers[j]);
input.close();
}
}
7-29 游戏:选出四张牌
public class Program7_29 {
public static void main(String[] args) {
int[] poker = new int[52];
String[] card = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
for(int i = 0; i < 52; i++)
poker[i] = i;
int count = 0;
while(true){
int sum = 0;
for(int i = 1; i <= 4; i++){
System.out.print(i + "\t");
int j = (int) (Math.random() * 52);
sum += j%13;
System.out.println(card[j%13]);
}
if(sum == 24) break;
count++;
System.out.println();
}
System.out.println("count: " + count);
}
}
7-30 模式识别方面:四个连续相等的数
import java.util.Scanner;
public class Program7_30 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of values: ");
int num = input.nextInt();
int[] values = new int[num];
System.out.print("Enter the values: ");
for (int i = 0; i < num; i++)
values[i] = input.nextInt();
if(isConsecutiveFour(values))
System.out.println("The list has consecutive fours");
else
System.out.println("The list has no consecutive fours");
input.close();
}
public static boolean isConsecutiveFour(int[] values){
for (int i = 0; i < values.length - 4; i++){
boolean flag = true;
for(int j = 1; j < 4; j++)
if(values[i+j] != values[i]) {
flag = false;
break;
}
if(flag)
return true;
}
return false;
}
}
7-31 合并两个有序列表
import java.util.Scanner;
public class Program7_31 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter list1: ");
int n1 = input.nextInt();
int[] list1 = new int[n1];
for (int i = 0; i < n1; i++)
list1[i] = input.nextInt();
System.out.print("Enter list2: ");
int n2 = input.nextInt();
int[] list2 = new int[n2];
for (int i = 0; i < n2; i++)
list2[i] = input.nextInt();
System.out.print("The merged list is ");
int[] ans = merge(list1, list2);
for (int i = 0; i < ans.length; i++)
System.out.print(ans[i] + " ");
System.out.println();
input.close();
}
public static int[] merge(int[] list1, int[] list2){
int i = 0, j = 0, n = 0;
int[] ans = new int[list1.length + list2.length];
while(i != list1.length || j != list2.length){
if(i == list1.length) {
ans[n] = list2[j];
j++;
n++;
continue;
}
if(j == list2.length) {
ans[n] = list1[i];
i++;
n++;
continue;
}
if(list1[i] <= list2[j]){
ans[n] = list1[i];
i++;
}else{
ans[n] = list2[j];
j++;
}
n++;
}
return ans;
}
}
7-32 划分列表
import java.util.Scanner;
public class Program7_32 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter list: ");
int num = input.nextInt();
int[] list = new int[num];
for(int i = 0; i < num; i++)
list[i] = input.nextInt();
partition(list);
System.out.print("After the partition. the list is ");
for (int i = 0; i < num; i++)
System.out.print(list[i] + " ");
System.out.println();
input.close();
}
public static int partition(int[] list){
int index = 0, large = 0;
for(int i = 1; i < list.length; i++){
if(list[i] < list[index]){
int temp = list[i];
list[i] = list[index];
list[index] = temp;
index = i;
}else{
if(large + index >= list.length)
break;
int temp = list[i];
list[i] = list[list.length - large - 1];
list[list.length - large - 1] = temp;
large++;
i--;
}
}
return index;
}
}
7-33 文化:中国生肖
import java.util.Scanner;
public class Program7_33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
String[] zodiac = {"monkey", "rooster", "dog", "pig", "rat", "ox",
"tiger", "rabbit", "dragon", "snake", "horse", "sheep"};
System.out.println(zodiac[year % 12]);
}
}
7-34 对字符串中的字符排序
import java.util.Scanner;
public class Program7_34 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = input.next();
System.out.println(sort(s));
}
public static char[] sort(String s){
int len = s.length();
char[] str = s.toCharArray();
for(int i = 0; i < len; i++){
int k = i;
for(int j = i+1; j < len; j++)
if(str[j] < str[k]) k = j;
char temp = str[i];
str[i] = str[k];
str[k] = temp;
}
return str;
}
}
7-35 游戏:猜字游戏
import java.util.Scanner;
public class Program7_35 {
public static void main(String[] args) {
String[] words = {"write", "that", "program", "java", "software", "system", "project", "chess"};
Scanner input = new Scanner(System.in);
char c;
do{
int missCount = 0;
int t = (int) (Math.random() * (words.length));
String str = words[t];
String m = "";
for (int i = 0; i < str.length(); i++)
m += '*';
while(str.compareTo(m) != 0){
System.out.print("(Guess) Enter a letter in word " + m + " > ");
char letter = input.next().charAt(0);
if(str.indexOf(letter) != -1){
if(m.indexOf(letter) != -1)
System.out.println(" " + letter + " is already in the word");
else{
String alter = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == letter)
alter += letter;
else
alter += m.charAt(i);
}
m = alter;
}
}else {
System.out.println(" " + letter + " is not in the word");
missCount++;
}
}
System.out.println("The word is " + str + ". " +
"You missed " + missCount + " time" + ((missCount > 1) ? 's' : ""));
System.out.print("Do you want to guess another word? Enter y or n > ");
c = input.next().charAt(0);
}while(c == 'y');
}
}