Java语言程序设计(基础篇)(原书第10版) 练习题答案 第7章

基础篇课后习题答案,做了大部分,虽然不一定是最佳代码,但是保证每个都能运行,如有更好的答案,欢迎讨论

 

7.1 指定等级

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入学生人数:");
    int num = scanner.nextInt();
    int[] grade = new int[num];
    System.out.print("请输入所有分数:");

    for (int i = 0; i < num; i++) {
        grade[i] = scanner.nextInt();
        if (grade[i] > 100 || grade[i] < 0) {
            System.out.print("无效成绩");
            System.exit(1);
        }
    }
    for (int i = 0; i < num; i++) {
        System.out.println("第" + (i + 1) + "位学生的分数是" + grade[i] + "分,对应的成绩为" + result(grade[i]));
    }
}

private static char result(int grade) {
    char[] result = {'A', 'B', 'C', 'D', 'F'};
    int i;
    if (grade >= 90 && grade <= 100) {
        i = 0;
    } else if (grade >= 80 && grade < 90) {
        i = 1;
    } else if (grade >= 70 && grade < 80) {
        i = 2;
    } else if (grade >= 60 && grade < 70) {
        i = 3;
    } else {
        i = 4;
    }
    return result[i];
}

 

7.2 数字倒置

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入10个整数:");
    int[] num = new int[10];
    for (int i = 0; i < 10; i++) {
        num[i] = scanner.nextInt();
    }
    for (int i : newNum(num)) {
        System.out.print(i + " ");
    }
}

private static int[] newNum(int[] num) {
    int tmp;
    for (int i = 0; i < num.length / 2; i++) {
        tmp = num[i];
        num[i] = num[num.length - 1 - i];
        num[num.length - 1 - i] = tmp;
    }
    return num;
}

 

7.3 计算数字出现的次数

public static void main(String[] args) {
    int[] num = createArrays();
    Arrays.sort(num);
    System.out.println("数据升序排列后为:" + Arrays.toString(num));
    for (int i = 0; i < num.length; i++) {
        if (i == 0 || (num[i] != num[i - 1])) {
            System.out.println(num[i] + "在数组中出现了" + getCount(num[i], num) + "次");
        }
    }
}

private static int[] createArrays() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入1~100之间的整数(以0作为结束):");
    int[] num = new int[100];
    int i = 0;
    int input;
    while (i >= 0) {
        input = scanner.nextInt();
        if (input != 0) {
            num[i] = input;
            i++;
        } else {
            break;
        }
    }
    int zeroIndex = getZeroIndex(num);
    int[] newNum = new int[zeroIndex];
    System.arraycopy(num, 0, newNum, 0, zeroIndex);
    return newNum;
}

private static int getZeroIndex(int[] num) {
    for (int i = 0; i < num.length; i++) {
        if (num[i] == 0) {
            return i;
        }
    }
    return -1;
}

private static int getCount(int indexNum, int[] num) {
    int count = 0;
    for (int i = 0; i < num.length; i++) {
        if (indexNum == num[i]) {
            count++;
        }
    }
    return count;
}

 

7.4 分析成绩

public static void main(String[] args) {
    int[] num = createArrays();
    double averagePoint = averagePoint(num);
    System.out.println("分数分别是:" + Arrays.toString(num));
    System.out.println("平均分是:" + averagePoint);
    countResult(num, averagePoint);
}

private static int[] createArrays() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入成绩(1~100之间的整数):");
    int[] num = new int[100];
    int i = 0;
    int input;
    while (i >= 0) {
        input = scanner.nextInt();
        if (input >= 0 && input <= 100) {
            num[i] = input;
            i++;
        } else if (input > 100) {
            System.out.print("输入的分数超出最大值!");
            System.exit(1);
        } else {
            break;
        }
    }
    int zeroIndex = getZeroIndex(num);
    int[] newNum = new int[zeroIndex];
    System.arraycopy(num, 0, newNum, 0, zeroIndex);
    return newNum;
}

private static int getZeroIndex(int[] num) {
    for (int i = 0; i < num.length; i++) {
        if (num[i] == 0) {
            return i;
        }
    }
    return -1;
}

private static double averagePoint(int[] num) {
    double averagePoint;
    int length = num.length;
    double totalPoint = 0;
    for (int i = 0; i < num.length; i++) {
        totalPoint = totalPoint + num[i];
    }
    averagePoint = totalPoint / length;
    return averagePoint;
}

private static void countResult(int[] num, double averagePoint) {
    int count1 = 0, count2 = 0;
    for (int i = 0; i < num.length; i++) {
        if ((double) num[i] >= averagePoint) {
            count1++;
        }
        if ((double) num[i] < averagePoint) {
            count2++;
        }
    }
    System.out.println("大于等于平均分的成绩个数为:" + count1);
    System.out.print("小于平均分的成绩个数为:" + count2);
}

 

7.5 打印不同的数

public static void main(String[] args) {
    System.out.print("请输入10个正整数:");
    int[] inputNumList = inputNumList();
    System.out.println("当前的数组为:" + Arrays.toString(inputNumList));
    resultNumList(inputNumList);
}

private static int[] inputNumList() {
    Scanner scanner = new Scanner(System.in);
    int[] inputNumList = new int[10];
    for (int i = 0; i < 10; i++) {
        inputNumList[i] = scanner.nextInt();
    }
    return inputNumList;
}

private static void resultNumList(int[] inputNumList) {
    int counts = 0;
    ArrayList resultNumList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        for (int j = i; j < 10; j++) {
            if (inputNumList[i] == inputNumList[j] && i != j) {
                inputNumList[j] = -1;
            }
        }
        if (inputNumList[i] != -1) {
            counts++;
            resultNumList.add(inputNumList[i]);
        }
    }
    System.out.println("其中不同的数字个数为:" + counts);
    System.out.print("最后的结果为:" + Arrays.toString(resultNumList.toArray()));
}

 

7.7 统计一位数的个数

public static void main(String[] args) {
    int[] numArrays = new int[100];
    int[] numCounts = new int[10];
    int i = 0;
    while (i < numArrays.length) {
        numArrays[i] = (int) (Math.random() * 10);
        System.out.print(numArrays[i] + " ");
        numCounts[numArrays[i]]++;
        i++;
        if (i % 10 == 0) {
            System.out.println();
        }
    }
    System.out.println("--------------------");
    for (int j = 0; j < numCounts.length; j++) {
        System.out.print(j + " 在数组中出现了 ");
        System.out.printf("%2d%s\n", numCounts[j], " 次");
    }
}

 

7.8 求数组的平均值

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double[] numList = new double[10];
    System.out.print("请输入10个数字:");
    for (int i = 0; i < numList.length; i++) {
        numList[i] = scanner.nextDouble();
    }
    double average = average(numList);
    System.out.print("这10个数的平均值是:" + average);
}

private static double average(double[] array) {
    double average = 0;
    for (double i : array) {
        average += i;
    }
    average /= 10;
    return average;
}

 

7.9 找出最小元素

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double[] array = new double[10];
    System.out.print("请输入10个数字:");
    for (int i = 0; i < array.length; i++) {
        array[i] = scanner.nextDouble();
    }
    System.out.print("这10个数字中最小值是:" + min(array));
}

private static double min(double[] array) {
    double min = array[0];
    for (double i : array) {
        if (min >= i) {
            min = i;
        }
    }
    return min;
}

 

7.10 找出最小元素的下标

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double[] array = new double[10];
    System.out.print("请输入10个数字:");
    for (int i = 0; i < array.length; i++) {
        array[i] = scanner.nextDouble();
    }
    System.out.print("这10个数字中最小值的下标是:" + minIndex(array));
}

private static int minIndex(double[] array) {
    int minIndex = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[minIndex] > array[i]) {
            minIndex = i;
        }
    }
    return minIndex;
}

 

7.12 倒置数组

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int[] numList = new int[10];
    System.out.print("请输入10个整数:");
    for (int i = 0; i < 10; i++) {
        numList[i] = scanner.nextInt();
    }
    System.out.println("生成的数组为:" + Arrays.toString(numList));
    numList = reverse(numList);
    System.out.print("倒置后的数组为:" + Arrays.toString(numList));
}

private static int[] reverse(int[] numList) {
    int[] newNumList = new int[numList.length];
    for (int i = 0; i < numList.length; i++) {
        newNumList[numList.length - 1 - i] = numList[i];
    }
    return newNumList;
}

 

7.13 随机数选择器

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    ArrayList numArrayList = new ArrayList<>();
    int[] numList;

    System.out.println("随机生成1~54的整数");
    System.out.println("----------------");
    System.out.print("请输入排除的数字(以0结束):");

    while (true) {
        int tmpNum = scanner.nextInt();
        if (tmpNum > 0 && tmpNum < 55) {
            numArrayList.add(tmpNum);
        } else if (tmpNum == 0) {
            break;
        } else {
            System.out.print("输入超出取值范围");
            System.exit(1);
            break;
        }
    }

    numList = new int[numArrayList.size()];
    for (int i = 0; i < numArrayList.size(); i++) {
        numList[i] = numArrayList.get(i);
    }
    System.out.println("排除的整数为:" + Arrays.toString(numList));

    int random = getRandom(numList);
    System.out.print("生成的随机数为:" + random);
}

private static int getRandom(int... numbers) {
    int randomNum = (int) (Math.random() * 54) + 1;
    for (int i : numbers) {
        if (randomNum == i) {
            randomNum = (int) (Math.random() * 54) + 1;
        }
    }
    return randomNum;
}

 

7.15 消除重复

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int[] list = new int[10];
    System.out.print("请输入10个整数:");
    for (int i = 0; i < list.length; i++) {
        list[i] = scanner.nextInt();
    }
    
    System.out.println("你输入的数组为:" + Arrays.toString(list));
    System.out.print("去除重复后的数组为:" + Arrays.toString(removeDuplicate(list)));
}

private static int[] removeDuplicate(int[] list) {
    int[] tmpList = new int[list.length];
    int listLength = 0;
    for (int i = 0; i < list.length; i++) {
        boolean isDuplicate = true;
        for (int j = i; j < list.length; j++) {
            if (i != j && list[i] == list[j]) {
                isDuplicate = false;
                break;
            }
        }

        if (isDuplicate) {
            tmpList[listLength] = list[i];
            listLength++;
        }
    }

    int[] newList = new int[listLength];
    System.arraycopy(tmpList, 0, newList, 0, listLength);
    return newList;
}

 

7.17 对学生排序

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

    int num;
    System.out.print("请输入学生的个数:");
    num = scanner.nextInt();

    String[] name = new String[num];
    double[] result = new double[num];
    for (int i = 0; i < num; i++) {
        System.out.print("请输入第" + (i + 1) + "学生的姓名:");
        name[i] = scanner.next();
        System.out.print("请输入第" + (i + 1) + "学生的成绩:");
        result[i] = scanner.nextDouble();
    }

    listSort(result, name, num);
}

private static void listSort(double[] result, String[] name, int num) {
    double tmpResult;
    String tmpName;
    for (int i = 0; i < num; i++) {
        for (int j = i; j < num; j++) {
            if (result[i] < result[j]) {
                tmpResult = result[j];
                result[j] = result[i];
                result[i] = tmpResult;

                tmpName = name[j];
                name[j] = name[i];
                name[i] = tmpName;
            }
        }
    }

    System.out.println("姓名           成绩");
    System.out.println("------------------");
    for (int i = 0; i < num; i++) {
        System.out.printf("%-1s%14.1f\n", name[i], result[i]);
    }
}

 

7.18 冒泡排序

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入十个数:");
    double[] list = new double[10];
    for (int i = 0; i < 10; i++) {
        list[i] = scanner.nextDouble();
    }
    System.out.println("原始数组为:" + Arrays.toString(list));
    System.out.print("排序后的数组为:" + Arrays.toString(arraySort(list)));
}

private static double[] arraySort(double[] list) {
    double tmp;
    for (int i = 0; i < list.length - 1; i++) {
        for (int j = 0; j < list.length - 1 - i; j++) {
            if (list[j] > list[j + 1]) {
                tmp = list[j + 1];
                list[j + 1] = list[j];
                list[j] = tmp;
            }
        }
    }
    return list;
}

 

7.19 检查数组排序

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int num;
    System.out.print("请输入数字(第一个数表示数组长度):");
    num = scanner.nextInt();
    int[] numArray = new int[num];
    for (int i = 0; i < num; i++) {
        numArray[i] = scanner.nextInt();
    }
    System.out.println("输入的数组为:" + Arrays.toString(numArray));
    if (isSorted(numArray)) {
        System.out.print("该数组已经按升序排列");
    } else {
        System.out.print("该数组没有按升序排列");
    }
}

private static boolean isSorted(int[] numArray) {
    int[] tmpArray = new int[numArray.length];
    System.arraycopy(numArray, 0, tmpArray, 0, numArray.length);
    Arrays.sort(tmpArray);
    return Arrays.equals(tmpArray, numArray);
}

 

7.20 修改选择排序法

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double[] numArray = new double[10];
    System.out.print("请输入10个数字:");
    for (int i = 0; i < numArray.length; i++) {
        numArray[i] = scanner.nextDouble();
    }
    System.out.print("排序后的数组为:" + Arrays.toString(arraySort(numArray)));
}

private static double[] arraySort(double[] numArray) {
    for (int i = numArray.length - 1; i > 0; i--) {
        double max = numArray[i];
        int index = numArray.length - 1;
        for (int j = i - 1; j >= 0; j--) {
            if (max < numArray[j]) {
                max = numArray[j];
                index = j;
            }
        }
        if (numArray[i] != max) {
            numArray[index] = numArray[i];
            numArray[i] = max;
        }
    }
    return numArray;
}

 

7.22 八皇后

public static void main(String[] args) {
    String[] queenList0 = new String[8];
    String[] queenList1 = new String[8];
    String[] queenList2 = new String[8];
    String[] queenList3 = new String[8];
    String[] queenList4 = new String[8];
    String[] queenList5 = new String[8];
    String[] queenList6 = new String[8];
    String[] queenList7 = new String[8];

    int[] queenIndex = queenIndex();

    queenList(queenList0, queenList1, queenList2,
            queenList3, queenList4, queenList5,
            queenList6, queenList7, queenIndex);

    queenPrint(queenList0, queenList1, queenList2, queenList3,
            queenList4, queenList5, queenList6, queenList7);
}

private static int[] queenIndex() {
    int[] queenIndex = new int[8];
    queenIndex[0] = (int) (Math.random() * 8);
    for (int i = 1; i < queenIndex.length; i++) {
        boolean inLoop = true;
        while (inLoop) {
            boolean isDuplicate = false;
            int queen = (int) (Math.random() * 8);
            for (int j = 0; j < i; j++) {
                if (queenIndex[j] == queen) {
                    isDuplicate = true;
                    break;
                }
            }
            if (queenIndex[i - 1] == queen + 1 ||
                    queenIndex[i - 1] == queen - 1) {
                isDuplicate = true;
            }
            if (!isDuplicate) {
                queenIndex[i] = queen;
                inLoop = false;
            }
        }
    }
    return queenIndex;
}

private static void queenList(String[] queenList0,
                              String[] queenList1,
                              String[] queenList2,
                              String[] queenList3,
                              String[] queenList4,
                              String[] queenList5,
                              String[] queenList6,
                              String[] queenList7,
                              int[] queenIndex) {
    queenList0[queenIndex[0]] = "Q";
    queenList1[queenIndex[1]] = "Q";
    queenList2[queenIndex[2]] = "Q";
    queenList3[queenIndex[3]] = "Q";
    queenList4[queenIndex[4]] = "Q";
    queenList5[queenIndex[5]] = "Q";
    queenList6[queenIndex[6]] = "Q";
    queenList7[queenIndex[7]] = "Q";

    for (int i = 0; i < queenList0.length; i++) {
        if (queenList0[i] == null) {
            queenList0[i] = " ";
        }
    }
    for (int i = 0; i < queenList1.length; i++) {
        if (queenList1[i] == null) {
            queenList1[i] = " ";
        }
    }
    for (int i = 0; i < queenList2.length; i++) {
        if (queenList2[i] == null) {
            queenList2[i] = " ";
        }
    }
    for (int i = 0; i < queenList3.length; i++) {
        if (queenList3[i] == null) {
            queenList3[i] = " ";
        }
    }
    for (int i = 0; i < queenList4.length; i++) {
        if (queenList4[i] == null) {
            queenList4[i] = " ";
        }
    }
    for (int i = 0; i < queenList5.length; i++) {
        if (queenList5[i] == null) {
            queenList5[i] = " ";
        }
    }
    for (int i = 0; i < queenList6.length; i++) {
        if (queenList6[i] == null) {
            queenList6[i] = " ";
        }
    }
    for (int i = 0; i < queenList7.length; i++) {
        if (queenList7[i] == null) {
            queenList7[i] = " ";
        }
    }
}

private static void queenPrint(String[] queenList0,
                               String[] queenList1,
                               String[] queenList2,
                               String[] queenList3,
                               String[] queenList4,
                               String[] queenList5,
                               String[] queenList6,
                               String[] queenList7) {
    for (String str : queenList0) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.println(" | ");
    for (String str : queenList1) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.println(" | ");
    for (String str : queenList2) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.println(" | ");
    for (String str : queenList3) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.println(" | ");
    for (String str : queenList4) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.println(" | ");
    for (String str : queenList5) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.println(" | ");
    for (String str : queenList6) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.println(" | ");
    for (String str : queenList7) {
        System.out.print(" | ");
        System.out.print(str);
    }
    System.out.print(" | ");
}

 

7.26 完全相同的数组

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入数组1(第一个数字表示数组长度):");
    int[] list1 = new int[scanner.nextInt()];
    for (int i = 0; i < list1.length; i++) {
        list1[i] = scanner.nextInt();
    }
    System.out.print("请输入数组2(第一个数字表示数组长度):");
    int[] list2 = new int[scanner.nextInt()];
    for (int i = 0; i < list2.length; i++) {
        list2[i] = scanner.nextInt();
    }
    if (equals(list1, list2)) {
        System.out.print("这两个数组完全相同");
    } else {
        System.out.print("这两个数组不完全相同");
    }
}

private static boolean equals(int[] list1, int[] list2) {
    return Arrays.equals(list1, list2);
}

 

7.27 相同的数组

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入数组1(第一个数字表示数组长度):");
    int[] list1 = new int[scanner.nextInt()];
    for (int i = 0; i < list1.length; i++) {
        list1[i] = scanner.nextInt();
    }
    System.out.print("请输入数组2(第一个数字表示数组长度):");
    int[] list2 = new int[scanner.nextInt()];
    for (int i = 0; i < list2.length; i++) {
        list2[i] = scanner.nextInt();
    }
    if (equals(list1, list2)) {
        System.out.print("这两个数组相同");
    } else {
        System.out.print("这两个数组不同");
    }
}

private static boolean equals(int[] list1, int[] list2) {
    Arrays.sort(list1);
    Arrays.sort(list2);
    return Arrays.equals(list1, list2);
}

 

7.28 数字组合

public static void main(String[] args) {
    int count = 0;
    Scanner scanner = new Scanner(System.in);
    int[] numList = new int[10];
    System.out.print("请输入10个整数:");
    for (int i = 0; i < numList.length; i++) {
        numList[i] = scanner.nextInt();
    }
    System.out.println("输入整数的数组为:" + Arrays.toString(numList));
    System.out.println("其中任意两个数字的组合如下:");
    int[] twoNum = new int[2];
    for (int i = 0; i <= 8; i++) {
        for (int j = i + 1; j <= 9; j++) {
            twoNum[0] = numList[i];
            twoNum[1] = numList[j];
            System.out.print(Arrays.toString(twoNum));
            count++;
        }
        System.out.println();
    }
    System.out.println("以上组合共有" + count + "种");
}

 

7.30 四个连续相等的数

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int[] numList;
    System.out.print("请输入数字的个数:");
    numList = new int[scanner.nextInt()];
    System.out.print("请输入数字:");
    for (int i = 0; i < numList.length; i++) {
        numList[i] = scanner.nextInt();
    }
    System.out.println("输入的数组为:" + Arrays.toString(numList));
    if (isRepetition(numList)) {
        System.out.print("数组内含有四个连续相等的数");
    } else {
        System.out.print("数组内没有四个连续相等的数");
    }
}

private static boolean isRepetition(int[] numList) {
    int count = 1;
    for (int i = 0; i <= numList.length - 4; i++) {
        for (int j = i + 1; j < numList.length; j++) {
            if (numList[i] == numList[j]) {
                count++;
            }
        }
        if (count < 4) {
            count = 1;
        }
    }
    return (count >= 4);
}

 

7.31 合并两个有序列表

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入数组1(第一个数字表示数组长度):");
    int[] list1 = new int[scanner.nextInt()];
    for (int i = 0; i < list1.length; i++) {
        list1[i] = scanner.nextInt();
    }
    System.out.print("请输入数组2(第一个数字表示数组长度):");
    int[] list2 = new int[scanner.nextInt()];
    for (int i = 0; i < list2.length; i++) {
        list2[i] = scanner.nextInt();
    }
    System.out.println("数组1为:" + Arrays.toString(list1));
    System.out.println("数组2为:" + Arrays.toString(list2));
    System.out.print("整合后的数组为:" + Arrays.toString(merge(list1, list2)));
}

private static int[] merge(int[] list1, int[] list2) {
    int[] newList = new int[list1.length + list2.length];
    System.arraycopy(list1, 0, newList, 0, list1.length);
    System.arraycopy(list2, 0, newList, list1.length, list2.length);
    Arrays.sort(newList);
    return newList;
}

 

7.34 字符串排序

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入字符串(由字母组成):");
    String str = scanner.next();
    System.out.print("排序后的字符串为:" + sort(str));
}

private static String sort(String str) {
    char[] chArray = new char[str.length()];
    String newStr = "";
    for (int i = 0; i < chArray.length; i++) {
        if (i != chArray.length - 1) {
            chArray[i] = str.substring(i, i + 1).charAt(0);
        } else {
            chArray[i] = str.substring(i).charAt(0);
        }
    }
    Arrays.sort(chArray);
    for (char ch : chArray) {
        newStr += String.valueOf(ch);
    }
    return newStr;
}

 


 

你可能感兴趣的:(Java语言程序设计(基础篇)(原书第10版) 练习题答案 第7章)