1. ホーム
  2. java

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

2022-02-22 07:39:31

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

6.1 五分位数の計算

public static void main(String[] args) {
    for (int i = 1; i <= 100; i++) {
        if (i % 10 == 0) {
            System.out.printf("%-6d\n", getPentagonalNumber(i));
        } else {
            System.out.printf("%-6d", getPentagonalNumber(i));
        }
    }
}

public static int getPentagonalNumber(int n) {
    return n * (3 * n - 1) / 2;
}

6.2 整数の和を求める

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter an integer: ");
    Long num = scanner.nextLong();
    System.out.print(num + "The sum of the digits is: " + sumDigits(num));
}

public static int sumDigits(long n) {
    int sumTotal = 0;
    char ch;
    String str = String.valueOf(n).toString();
    for (int i = 0; i < str.length(); i++) {
        ch = str.charAt(i);
        sumTotal = sumTotal + Integer.parseInt(String.valueOf(ch));
    }
    return sumTotal;
}

6.3 エコー積算値

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter an integer value: ");
    int num = scanner.nextInt();
    if (isPalindrome(num) == true) {
        System.out.println("This number is the return number");
    } else {
        System.out.println("This number is not a return");
    }
}


public static boolean isPalindrome(int number) {
    return (number == reverse(number));
}

public static int reverse(int number) {
    int revNum = 0;
    while (number ! = 0) {
        revNum = number % 10 + (revNum * 10);
        number /= 10;
    }
    return revNum;
}

6.4 逆方向の整数を表示する

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter an integer: ");
    int num = scanner.nextInt();
    System.out.print("The reverse order output of the number is: " + reverse(num));
}

public static int reverse(int number) {
    int result = 0;
    while (number ! = 0) {
        result = (result * 10) + number % 10;
        number /= 10;
    }
    return result;
}

6.5 3つの数値の並べ替え

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter three numbers: ");
    double num1, num2, num3;
    num1 = scanner.nextDouble();
    num2 = scanner.nextDouble();
    nextDouble(); num3 = scanner.nextDouble(); num3 = scanner.nextDouble();
    displaySortedNumbers(num1, num2, num3);

}

public static void displaySortedNumbers(double num1, double num2, double num3) {
    double changeNum;
    if (num1 < num2) {
        changeNum = num1;
        num1 = num2;
        num2 = changeNum;
    }
    if (num2 < num3) {
        changeNum = num2;
        num2 = num3;
        num3 = changeNum;
    }
    if (num1 < num2) {
        changeNum = num1;
        num1 = num2;
        num2 = changeNum;
    }
    System.out.print("The result after ascending order is: " + num3 + "," + num2 + "," + num1);
}

6.6 パターンを表示する

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter a value: ");
    int n = scanner.nextInt();
    displayPattern(n);
}

public static void displayPattern(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = n - i; j >= 1; j--) {
            System.out.printf("%3s", "");
        }
        for (int j = i; j >= 1; j--) {
            System.out.printf("%3d", j);
        }
        System.out.println();
    }
}

<スパン 6.7 将来の投資価値の計算

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the investment amount: ");
    double investmentAmount = scanner.nextDouble();
    System.out.print("Please enter the annual interest rate: ");
    double monthlyInterestRate = scanner.nextDouble();
    monthlyInterestRate = monthlyInterestRate / 1200;
    System.out.printf("%-8s%15s\n", "Years", "Future Value");
    for (int i = 1; i <= 30; i++) {
        System.out.printf("%-8d%15.2f\n", i, futureInvestmentValue(investmentAmount, monthlyInterestRate, i));
    }
}

public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years) {
    double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), (years * 12));
    return futureInvestmentValue;
}


6.8セルシウス換算

public static void main(String[] args) {
    System.out.printf("%-8s%-8s%8s%8s\n", "Celsius", "Fahrenheit", "Fahrenheit", "Celsius");
    System.out.println("----------------------------------------");
    for (int tpr1 = 40, tpr2 = 120; tpr1 >= 31 && tpr2 >= 30; tpr1 --, tpr2 -= 10) {
        System.out.printf("%-10.1f%-8.1f", (double) tpr1, celsiusToFahrenheit((double) tpr1));
        System.out.printf("%11.1f%11.2f\n", (double) tpr2, fahrenheitToCelsius((double) tpr2));
    }
}

public static double celsiusToFahrenheit(double celsius) {
    return (9.0 / 5) * celsius + 32;
}

public static double fahrenheitToCelsius(double fahrenheit) {
    return (5.0 / 9) * (fahrenheit - 32);
}

<スパン 6.9フィート換算

public static void main(String[] args) {
    System.out.printf("%-9s%-8s%10s%9s\n", "ft", "m", "m", "m", "ft");
    System.out.println("----------------------------------------");
    for (int i = 1, j = 20; i <= 10 && j <= 65; i++, j += 5) {
        System.out.printf("%-10.1f%-8.3f", (double) i, footToMeter((double) i));
        System.out.printf("%11.1f%11.3f\n", (double) j, meterToFoot((double) j));
    }
}

public static double footToMeter(double foot) {
    return foot * 0.305;
}

public static double meterToFoot(double meter) {
    return meter * 3.279;
}

6.12 文字を表示する

public static void main(String[] args) {
    printChars('1', 'Z', 10);
}

public static void printChars(char ch1, char ch2, int numLine) {
    int num = 1;
    for (int i = (int) ch1; i <= (int) ch2; i++) {
        System.out.printf("%2c", (char) i);
        if (num % numLine == 0) {
            System.out.println();
        }
        num++;
    }
}

6.13 シリーズの総和

public static void main(String[] args) {
    System.out.println("i" + " " + "m(i)");
    System.out.println("--------------------");
    for (int i = 1; i <= 20; i++) {
        System.out.printf("%-2d%17.4f\n", i, subTotal(i));
    }
}

public static double subTotal(int i) {
    double result = 0;
    for (int j = 1; j <= i; j++) {
        result = result + ((double) j / ((double) j + 1));
    }
    return result;
}

6.14 πの見積もり

public static void main(String[] args) {
    System.out.println("i" + " " + "m(i)");
    System.out.println("-------------------");
    for (int i = 1; i <= 901; i += 100) {
        System.out.printf("%-3d%15.4f\n", i, getResult(i));
    }
}

public static double getResult(int i) {
    double result = 0;
    for (int j = 1; j <= i; j++) {
        result = result + Math.pow(-1, j + 1) / (2 * j - 1);
    }
    result = result * 4;
    return result;
}

6.16 1年間の日数

public static void main(String[] args) {
    System.out.println("year" + " " + "number of days");
    System.out.println("-------------------");
    for (int i = 2000; i <= 2020; i++) {
        System.out.printf("%-4d%14d\n", i, daysOfYear(i));
    }
}

public static int daysOfYear(int year) {
    if (isLeapYear(year)) {
        return 366;
    } else return 365;
}

public static boolean isLeapYear(int year) {
    return ((year % 4 == 0 && year % 100 ! = 0) || (year % 400 == 0));
}

6.17 0と1の行列を表示する

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter a value: ");
    int n = scanner.nextInt();
    printMatrix(n);
}

public static void printMatrix(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            System.out.print(Math.round(Math.random()) + " ");
        }
        System.out.println();
    }
}

6.18 パスワードを検出する

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the password: ");
    String str = scanner.nextLine();
    switch (checkPassword(str)) {
        case 0:
            System.out.print("Password must be more than 8 digits! ");
            break;
        case 1:
            System.out.print("Password must contain only characters and numbers! ");
            break;
        case 2:
            System.out.print("Password must contain at least two numbers! ");
            break;
        default:
            System.out.print("Password check passed! ");
            break;
    }

}

public static int checkPassword(String pwd) {
    int numDigit = 0;
    int numLetter = 0;
    if (pwd.length() >= 8) {
        for (int i = 0; i < pwd.length(); i++) {
            if (Character.isDigit(pwd.substring(i, i + 1).charAt(0)) ||
                Character.isLetter(pwd.substring(i, i + 1).charAt(0))) { if (Character.isLetter(pwd.substring(i, i + 1).charAt(0))
                if (Character.isDigit(pwd.substring(i, i + 1).charAt(0))) {
                    numDigit++;
                }
                if (Character.isLetter(pwd.substring(i, i + 1).charAt(0))) {
                    numLetter++;
                }
            } else {
                return 1;
            }
        }
        if (numDigit >= 2 && numLetter > 0) {
            return 3;
        } else if (numDigit >= 2 && numLetter == 0) {
            return 1;
        } else if (numDigit == 0 && numLetter > 0) { return 1; }
            return 1;
        } else return 2;
    } else {
        return 0;
    }
}

6.20 文字列の文字数

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the string: ");
    String s = scanner.nextLine();
    System.out.println("The string contains a total of " + countLetters(s) + "letters");
}

public static int countLetters(String s) {
    int num = 0;
    for (int i = 0; i < s.length(); i++) {
        if (Character.isLetter(s.charAt(i))) {
            num++;
        }
    }
    return num;
}

6.21 キーパッドによる電話

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the string: ");
    String str = scanner.nextLine();
    System.out.print("The corresponding numeric keyboard is: " + changeToNum(str));
}

public static String changeToNum(String str) {
    StringBuffer toNumBuffer = new StringBuffer();
    for (int i = 0; i < str.length(); i++) {
        char ch = Character.toLowerCase(str.charAt(i));
        if (ch == 'a' || ch == 'b' || ch == 'c') {
            toNumBuffer.append("2");
        } else if (ch == 'd' || ch == 'e' || ch == 'f') {
            toNumBuffer.append("3");
        } else if (ch == 'g' || ch == 'h' || ch == 'i') {
            toNumBuffer.append("4");
        } else if (ch == 'j' || ch == 'k' || ch == 'l') {
            toNumBuffer.append("5");
        } else if (ch == 'm' || ch == 'n' || ch == 'o') {
            toNumBuffer.append("6");
        } else if (ch == 'p' || ch == 'q' || ch == 'r' || ch == 's') {
            toNumBuffer.append("7");
        } else if (ch == 't' || ch == 'u' || ch == 'v') {
            toNumBuffer.append("8");
        } else if (ch == 'w' || ch == 'x' || ch == 'y' || ch == 'z') {
            toNumBuffer.append("9");
        } else if (ch == ' ') {
            toNumBuffer.append("0");
        } else if (ch == '+') {
            toNumBuffer.append("*");
        } else {
            toNumBuffer.append(str.charAt(i));
        }
    }
    return toNumBuffer.toString();
}

6.23 文字の出現回数の指定

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter a string of characters: ");
    String str = scanner.nextLine();
    System.out.print("Please enter the characters to be calculated: ");
    String strLetter = scanner.nextLine();
    char ch = strLetter.charAt(0);
    System.out.print(ch + "The number of occurrences in " + str + " is: " + count(str, ch) + "times");
}

public static int count(String str, char ch) {
    int num = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == ch) {
            num++;
        }
    }
    return num;
}


6.25 ミリ秒を時間、分、秒に変換する

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter milliseconds: ");
    long ms = scanner.nextLong();
    System.out.print("The converted time is:" + convertMillis(ms));
}


public static String convertMillis(long millis) {
    long totalSecond = millis / 1000;
    long hour = totalSecond / 3600;
    long min = (totalSecond - (hour * 3600)) / 60;
    long second = totalSecond - (hour * 3600) - (min * 60);
    return hour + ":" + min + ":" + second;
}

6.26回文

public static void main(String[] args) {
    int num = 2;
    int count = 0;
    while (count < 100) {
        if (isPalindrome(num) && isPrime(num)) {
            count++;
            System.out.printf("%-7d", num);
            if (count % 10 == 0) {
                System.out.println();
            }
        }
        num++;
    }
}

private static boolean isPalindrome(int num) {
    int reNum = 0;
    int numTmp = num;
    while (numTmp ! = 0) {
        reNum = numTmp % 10 + (reNum * 10);
        numTmp = numTmp / 10;
    }
    return num == reNum;
}

private static boolean isPrime(int num) {
    for (int i = 2; i < num; i++) {
        if (num % i == 0)
            return false;
    }
    return true;
}

6.27 逆プリム

public static void main(String[] args) {
    int num = 11;
    int count = 0;
    while (count < 100) {
        if (notPalindrome(num) && isPrime(num)) {
            count++;
            System.out.printf("%-7d", num);
            if (count % 10 == 0) {
                System.out.println();
            }
        }
        num++;
    }
}

private static boolean notPalindrome(int num) {
    int reNum = 0;
    int numTmp = num;
    while (numTmp ! = 0) {
        reNum = numTmp % 10 + (reNum * 10);
        numTmp = numTmp / 10;
    }
    return num ! = reNum;
}

private static boolean isPrime(int num) {
    for (int i = 2; i < num; i++) {
        if (num % i == 0)
            return false;
    }
    int reNum = 0;
    while (num ! = 0) {
        reNum = num % 10 + (reNum * 10);
        num = num / 10;
    }
    for (int i = 2; i < reNum; i++) {
        if (reNum % i == 0)
            return false;
    }
    return true;
}

6.28 メルセンヌ素数

public static void main(String[] args) {
    System.out.println("p 2^p-1");
    System.out.println("----------------------");
    int num;
    for (int i = 2; i <= 31; i++) {
        num = (int) (Math.pow(2, i) - 1);
        if (isPrime(i) && isPrime(num)) {
            System.out.printf("%-2d%20d\n", i, num);
        }
    }
}

private static boolean isPrime(int num) {
    for (int i = 2; i < num; i++) {
        if (num % i == 0)
            return false;
    }
    return true;
}

6.29 Bis素数

public static void main(String[] args) {
    for (int i = 2; i <= 998; i++) {
        if (isPrime(i) && isPrime(i + 2)) {
            System.out.println("(" + i + "," + (i + 2) + ")");
        }
    }
}

private static boolean isPrime(int num) {
    for (int i = 2; i < num; i++) {
        if (num % i == 0)
            return false;
    }
    return true;
}

<スパン 6.30 ダブル・ダイス・ギャンブル

private static int count = 0;

public static void main(String[] args) {
    int num1 = (int) (Math.random() * 6) + 1;
    int num2 = (int) (Math.random() * 6) + 1;
    System.out.println("You voted " + num1 + "+" + num2 + "=" + (num1 + num2));
    isWin(num1, num2);
    System.out.print("Total throws" + count + "times");
}

private static void isWin(int num1, int num2) {
    int sum = num1 + num2;
    if (sum == 2 || sum == 3 || sum == 12) {
        System.out.println("You lose! ");
        count++;
    } else if (sum == 7 || sum == 11) {
        System.out.println("You win! ");
        count++;
    } else {
        count++;
        int result = 0;
        while (result == 0) {
            System.out.print("Please continue! ");
            Scanner scanner = new Scanner(System.in);
            scanner.nextLine();
            result = playAgain(num1, num2);
            count++;
        }
    }
}

private static int playAgain(int num1, int num2) {
    int sum = num1 + num2;
    int num1_new = (int) (Math.random() * 6) + 1;
    int num2_new = (int) (Math.random() * 6) + 1;
    System.out.println("You voted " + num1_new + "+" + num2_new + "=" + (num1_new + num2_new));
    if (num1_new + num2_new == sum) {
        System.out.println("You win! ");
        return 1;
    } else if (num1_new + num2_new == 7) {
        System.out.println("You lose! ");
        return 1;
    } else {
        return 0;
    }
}


6.31 クレジットカード番号の正当性

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter the 16-digit bank card number: ");
    long cardNum = input.nextLong();
    if (isValidCard(cardNum)) {
        System.out.print("This card number is valid! ");
    } else {
        System.out.print("This card number is invalid! ");
    }
}

private static boolean isValidCard(long cardNum) {
    return (oddCount(cardNum) + evenCount(cardNum)) % 10 == 0;
}

private static int oddCount(long cardNum) {
    int oddCount = 0;
    int odd;
    char oddChar;
    for (int i = 15; i >= 1; i = i - 2) {
        oddChar = String.valueOf(cardNum).charAt(i);
        odd = Integer.parseInt(String.valueOf(oddChar));
        oddCount = oddCount + odd;
    }
    return oddCount;
}

private static int evenCount(long cardNum) {
    int evenCount = 0;
    int even;
    int evenNew;
    char evenChar;
    for (int i = 14; i >= 0; i = i - 2) {
        evenChar = String.valueOf(cardNum).charAt(i);
        even = Integer.parseInt(String.valueOf(evenChar));
        if (even * 2 >= 10) {
            evenNew = even * 2 - 9;
        } else {
            evenNew = even * 2;
        }
        evenCount = evenCount + evenNew;
    }
    return evenCount;
}

6.32 サイコロのゲーム統計

private static int count = 0;

public static void main(String[] args) {
    for (int i = 1; i <= 1000; i++) {
        startPlay();
    }
    System.out.print("Total thrown " + count + "times");
}

private static void startPlay() {
    int num1 = (int) (Math.random() * 6) + 1;
    int num2 = (int) (Math.random() * 6) + 1;
    System.out.println("You voted " + num1 + "+" + num2 + "=" + (num1 + num2));
    isWin(num1, num2);
}

private static void isWin(int num1, int num2) {
    int sum = num1 + num2;
    if (sum == 2 || sum == 3 || sum == 12) {
        System.out.println("You lose! ");
        count++;
    } else if (sum == 7 || sum == 11) {
        System.out.println("You win! ");
        count++;
    } else {
        count++;
        int result = 0;
        while (result == 0) {
            System.out.print("Please continue! ");
            result = playAgain(num1, num2);
            count++;
        }
    }
}

private static int playAgain(int num1, int num2) {
    int sum = num1 + num2;
    int num1_new = (int) (Math.random() * 6) + 1;
    int num2_new = (int) (Math.random() * 6) + 1;
    System.out.println("You voted " + num1_new + "+" + num2_new + "=" + (num1_new + num2_new));
    if (num1_new + num2_new == sum) {
        System.out.println("You win! ");
        return 1;
    } else if (num1_new + num2_new == 7) {
        System.out.println("You lose! ");
        return 1;
    } else {
        return 0;
    }
}

6.35 五角形の面積

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the side length of the pentagon: ");
    double side = scanner.nextDouble();
    System.out.print("The area is: " + area(side));
}

private static double area(double side) {
    return Math.round((5 * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 5)) * 100) / 100d;
}


6.36 正多角形の面積

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the number of sides of the polygon: ");
    int n = scanner.nextInt();
    System.out.print("Please enter the length of the side of the polygon: ");
    double side = scanner.nextDouble();
    System.out.print("The area is: " + area(n, side));
}

private static double area(int n, double side) {
    return Math.round((n * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / n)) * 100) / 100d;
}

6.37 整数の書式設定

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter an integer: ");
    int number = scanner.nextInt();
    System.out.print("Please enter the number of prefix strings: ");
    int width = scanner.nextInt();
    System.out.print("Formatted as:" + format(number, width));
}

private static String format(int number, int width) {
    StringBuffer str = new StringBuffer();
    for (int i = 1; i <= width - String.valueOf(number).length(); i++) {
        str = str.append("0");
    }
    str.append(String.valueOf(number));
    return str.toString();
}


6.38 ランダム文字の生成

public static void main(String[] args) {
    for (int i = 1; i <= 100; i++) {
        System.out.print(getRandomUpperCaseLetter() + " ");
        if (i % 10 == 0) {
            System.out.println();
        }
    }
    for (int i = 1; i <= 100; i++) {
        System.out.print(getRandomDigitCharacter() + " ");
        if (i % 10 == 0) {
            System.out.println();
        }
    }
}

private static char getRandomUpperCaseLetter() {
    return getRandomCharacter('A', 'Z');
}

private static char getRandomDigitCharacter() {
    return getRandomCharacter('0', '9');
}

private static char getRandomCharacter(char ch1, char ch2) {
    return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}