1. ホーム
  2. java

Java言語プログラミング(基礎編)(第10版)練習問題解答編 第7章

2022-02-15 12:59:15

Fundamentalsの章にあるほとんどのコース後の練習問題の解答です。必ずしもベストなコードではありませんが 保証する それぞれの作品について、より良い答えがあれば、遠慮なく議論してください。

7.1 レベルの割り当て

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the number of students: ");
    int num = scanner.nextInt();
    int[] grade = new int[num];
    System.out.print("Please enter all grades: ");

    for (int i = 0; i < num; i++) {
        grade[i] = scanner.nextInt();
        if (grade[i] > 100 || grade[i] < 0) {
            System.out.print("invalid grade");
            System.exit(1);
        }
    }
    for (int i = 0; i < num; i++) {
        System.out.println("The "first" + (i + 1) + "student's score is " + grade[i] + "the corresponding grade is " + 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("Please enter 10 integers: ");
    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("Data in ascending order is: " + Arrays.toString(num));
    for (int i = 0; i < num.length; i++) {
        if (i == 0 || (num[i] ! = num[i - 1])) {
            System.out.println(num[i] + "appears in the array " + getCount(num[i], num) + "times");
        }
    }
}

private static int[] createArrays() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter an integer between 1 and 100 (ending with 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("The scores are: " + Arrays.toString(num));
    System.out.println("The average score is: " + averagePoint);
    countResult(num, averagePoint);
}

private static int[] createArrays() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter grades (integers between 1 and 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("The score entered exceeded the maximum! ");
            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("The number of scores greater than or equal to the average score is: " + count1);
    System.out.print("The number of scores less than the average is: " + count2);
}


7.5 異なる数字を印刷する

public static void main(String[] args) {
    System.out.print("Please enter 10 positive integers: ");
    int[] inputNumList = inputNumList();
    System.out.println("The current array is: " + 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<Integer> 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("where the number of different numbers is: " + counts);
    System.out.print("The final result is: " + Arrays.toString(resultNumList.toArray()));
}

7.7 1桁の数の数え方

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 + " appears in the array ");
        System.out.printf("%2d%s\n", numCounts[j], " times");
    }
}

7.8 配列の平均を求める

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    double[] numList = new double[10];
    System.out.print("Please enter 10 numbers: ");
    for (int i = 0; i < numList.length; i++) {
        numList[i] = scanner.nextDouble();
    }
    double average = average(numList);
    System.out.print("The average of these 10 numbers is: " + 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("Please enter 10 numbers: ");
    for (int i = 0; i < array.length; i++) {
        array[i] = scanner.nextDouble();
    }
    System.out.print("The smallest of these 10 numbers is: " + 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("Please enter 10 numbers: ");
    for (int i = 0; i < array.length; i++) {
        array[i] = scanner.nextDouble();
    }
    System.out.print("The subscript of the smallest of these 10 numbers is: " + 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("Please enter 10 integers: ");
    for (int i = 0; i < 10; i++) {
        numList[i] = scanner.nextInt();
    }
    System.out.println("The generated array is: " + Arrays.toString(numList));
    numList = reverse(numList);
    System.out.print("The inverted array is: " + 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<Integer> numArrayList = new ArrayList<>();
    int[] numList;

    System.out.println("Randomly generate integers from 1 to 54");
    System.out.println("----------------");
    System.out.print("Please enter the excluded numbers (ending with 0): ");

    while (true) {
        int tmpNum = scanner.nextInt();
        if (tmpNum > 0 && tmpNum < 55) {
            numArrayList.add(tmpNum);
        } else if (tmpNum == 0) {
            break;
        } else {
            System.out.print("Input out of range");
            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("The excluded integers are: " + Arrays.toString(numList));

    int random = getRandom(numList);
    System.out.print("The random number generated is: " + 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("Please enter 10 integers: ");
    for (int i = 0; i < list.length; i++) {
        list[i] = scanner.nextInt();
    }
    
    System.out.println("The array you entered is: " + Arrays.toString(list));
    System.out.print("The array after removing duplicates is: " + 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("Please enter the number of students: ");
    num = scanner.nextInt();

    String[] name = new String[num];
    double[] result = new double[num];
    for (int i = 0; i < num; i++) {
        System.out.print("Please enter the first " + (i + 1) + "Student's name: ");
        name[i] = scanner.next();
        System.out.print("Please enter the first " + (i + 1) + "Student's grade: ");
        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("Name Grade");
    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("Please enter ten numbers: ");
    double[] list = new double[10];
    for (int i = 0; i < 10; i++) {
        list[i] = scanner.nextDouble();
    }
    System.out.println("The original array is: " + Arrays.toString(list));
    System.out.print("The sorted array is: " + 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("Please enter the number (the first number indicates the length of the array): ");
    num = scanner.nextInt();
    int[] numArray = new int[num];
    for (int i = 0; i < num; i++) {
        numArray[i] = scanner.nextInt();
    }
    System.out.println("The input array is: " + Arrays.toString(numArray));
    if (isSorted(numArray)) {
        System.out.print("The array has been sorted in ascending order");
    } else {
        System.out.print("The array is not in ascending order");
    }
}

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("Please enter 10 numbers: ");
    for (int i = 0; i < numArray.length; i++) {
        numArray[i] = scanner.nextDouble();
    }
    System.out.print("The sorted array is: " + 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 : que

7.26 同一配列

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the array 1 (the first number indicates the length of the array): ");
    int[] list1 = new int[scanner.nextInt()];
    for (int i = 0; i < list1.length; i++) {
        list1[i] = scanner.nextInt();
    }
    System.out.print("Please enter array 2 (the first number indicates the length of the array): ");
    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("These two arrays are identical");
    } else {
        System.out.print("These two arrays are not identical");
    }
}

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("Please enter the array 1 (the first number indicates the length of the array): ");
    int[] list1 = new int[scanner.nextInt()];
    for (int i = 0; i < list1.length; i++) {
        list1[i] = scanner.nextInt();
    }
    System.out.print("Please enter array 2 (the first number indicates the length of the array): ");
    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("These two arrays are the same");
    } else {
        System.out.print("These two arrays are different");
    }
}

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("Please enter 10 integers: ");
    for (int i = 0; i < numList.length; i++) {
        numList[i] = scanner.nextInt();
    }
    System.out.println("The array of input integers is: " + Arrays.toString(numList));
    System.out.println("The combination of any two of these numbers is as follows:");
    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("The above combination has a total of " + count + "kind");
}

7.30 連続する4つの同数

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int[] numList;
    System.out.print("Please enter the number of numbers: ");
    numList = new int[scanner.nextInt()];
    System.out.print("Please enter the number: ");
    for (int i = 0; i < numList.length; i++) {
        numList[i] = scanner.nextInt();
    }
    System.out.println("The input array is: " + Arrays.toString(numList));
    if (isRepetition(numList)) {
        System.out.print("The array contains four consecutive equal numbers");
    } else {
        System.out.print("The array does not contain four consecutive equal numbers");
    }
}

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 2つの順序付きリストをマージする

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the array 1 (the first number indicates the length of the array): ");
    int[] list1 = new int[scanner.nextInt()];
    for (int i = 0; i < list1.length; i++) {
        list1[i] = scanner.nextInt();
    }
    System.out.print("Please enter array 2 (the first number indicates the length of the array): ");
    int[] list2 = new int[scanner.nextInt()];
    for (int i = 0; i < list2.length; i++) {
        list2[i] = scanner.nextInt();
    }
    System.out.println("array1 is: " + Arrays.toString(list1));
    System.out.println("array2 is: " + Arrays.toString(list2));
    System.out.print("The integrated array is: " + 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("Please enter a string (consisting of letters): ");
    String str = scanner.next();
    System.out.print("The sorted string is: " + 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;
}