第六章第三十五题(几何:五边形的面积)(Geometry: area of a pentagon) – 编程练习题答案

6.35(几何:五边形的面积)五边形的面积可以使用下面的公式计算:

编写一个方法,使用下面的方法头来返回五边形的面积。

public static double area(double side)

编写一个主方法,提示用户输入五边形的边,然后显示它的面积。

下面是一个运行示例:

Enter the side:5.5

The area of the pentagon is 52.044441
 

6.35(Geometry: area of a pentagon)The area of a pentagon can be computed using the following formula:

Write a method that returns the area of a pentagon using the following header:

public static double area(double side)

Write a main method that prompts the user to enter the side of a pentagon and displays its area.

Here is a sample run:

Enter the side:5.5

The area of the pentagon is 52.044441
 

下面是参考答案代码:

// https://cn.fankuiba.com
import java.util.Scanner;

public class Ans6_35_page205 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the side: ");
        double side = input.nextDouble();
        System.out.println("The area of the pentagon is "+area(side));
    }
    public static double area(double side) {
        return  (5 * side * side) / (4 * Math.tan(Math.PI / 5));
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)更多内容

第六章第三十六题(几何:正多边形的面积)(Geometry: area of a regular polygon) – 编程练习题答案

*6.36(几何:正多边形的面积)正多边形是一个n条边的多边形,它的每条边的长度都相等,而且所有角的角度也相等(即多边形既是等边又等角的)。计算正多边形面积的公式是:

使用下面的方法头编写方法,返回正多边形的面积:

public static double area(int n, double side)

编写一个main方法,提示用户输入边的个数以及正多边形的边长,然后显示它的面积。

下面是一个运行示例:

Enter the number of sides: 5

Enter the side:6.5

The area of the polygon is 72.690170
 

*6.36(Geometry: area of a regular polygon) A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree (i.e., the polygon is both equilateral and equiangular). The formula for computing the area of a regular polygon is

Write a method that returns the area of a regular polygon using the following header:

public static double area(int n, double side)

Write a main method that prompts the user to enter the number of sides and the side of a regular polygon and displays its area.

Here is a sample run:
 
Enter the number of sides: 5

Enter the side:6.5

The area of the polygon is 72.690170
 

下面是参考答案代码:

// https://cn.fankuiba.com
import java.util.Scanner;

public class Ans6_36_page205 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the side: ");
        double side = input.nextDouble();
        System.out.print("Enter the number of sides: ");
        int n = input.nextInt();
        System.out.println("The area of the pentagon is "+area(n,side));
    }
    public static double area(int n, double side) {
        return  (n * side * side) / (4 * Math.tan(Math.PI / 5));
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)更多内容

第六章第三十七题(格式化整数)(Format an integer) – 编程练习题答案

6.37(格式化整数)使用下面的方法头编写一个方法,用于将整数格式化为指定宽度:

public static String format(int number, int width)

方法为数字number返回一个带有一个或多个以0作为前缀的字符串。字符串的位数就是宽度。比如,format(34,4)返回0034,format(34,5)返回00034。如果数字宽于指定宽度,方法返回该数字的字符串表示。比如,format(34,1)返回34。

6.37(Format an integer)Write a method with the following header to format the integer with the specified width.

public static String format(int number, int width)

The method returns a string for the number with one or more prefix 0s. The size of the string is the width. For example, format(34, 4) returns 0034 and format(34, 5) returns 00034. If the number is longer than the width, the method returns the string representation for the number. For example, format(34, 1) returns 34.
Write a test program that prompts the user to enter a number and its width, and displays a string returned by invoking format(number, width).

下面是参考答案代码:

// https://cn.fankuiba.com
import java.util.Scanner;

public class Ans6_37_page205 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();
        System.out.print("Enter the number width: ");
        int width = input.nextInt();
        System.out.println(format(number,width));
    }
    public static String format(int number, int width) {
        String format = "";
        int numberLenth = (number+"").length();
        if (numberLenth < width) {
            for (int i = 1; i <=width-numberLenth; i++)
                format = format + "0";
            return format+number;
        }
        else
            return ""+number;// String strNumber = String.valueOf(number)
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)更多内容

第六章第三十一题(金融应用:信用卡号的合法性验证)(Financial: credit card number validation) – 编程练习题答案

**6.31(金融应用:信用卡号的合法性验证)信用卡号遵循某种模式。一个信用卡号必须是13到16位的整数。它的开头必须是:

4,指Visa卡

5,指Master卡

37,指American Express 卡

6,指Discover卡

1954年,IBM的Hans Luhn提出一种算法,用于验证信用卡号的有效性。这个算法在确定输入的卡号是否正确,或者这张信用卡是否被扫描仪正确扫描方面是非常有用的。遵循这个合法性检测可以生成所有的信用卡号,通常称之为Luhn检测或者Mod 10检测,可以如下描述(为了方便解释,假设卡号4388576018402626):

1.从右到左对偶数位数字翻倍。如果对某个数字翻倍之后的结果是一个两位数,那么就将这两位加在一起得到一位数。

2.现在将第一步得到的所有一位数相加。

3.将卡号里从右到左奇数位上的所有数字相加。

4.将第二步和第三步得到的结果相加。

5.如果第四步得到的结果能被10整除,那么卡号是合法的;否则,卡号是不合法的。例如,号码4388576018402626是不合法的,但是号码4388576018410707是合法的。

编写程序,提示用户输入一个long型整数的信用卡号码,显示这个数字是合法的还是非法的。
使用下面的方法设计程序:
public static boolean isValid(long number)

public static int sumOfDoubleEvenPlace(long number)

public static int getDigit(int number)

public static int sumOfOddPlace(long number)

public static boolean prefixMatched(long number, int d)

public static int getSize(long d)

public static long getPrefix(long number, int k)

下面是程序的运行示例:(你也可以通过将输入作为一个字符串读入,以及对字符串进行处理来验证信用卡卡号。)

Enter a credit card number as a long integer: 4388576018410707
4388576018410707 is valid

Enter a credit card number as a long integer: 4388576018402626
4388576018402626 is invalid

**6.31(Financial: credit card number validation) Credit card numbers follow certain patterns. A credit card number must have between 13 and 16 digits. It must start with

4 for Visa cards

5 for Master cards

37 for American Express cards

6 for Discover cards

In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine whether a card number is entered correctly, or whether a credit card is scanned correctly by a scanner. Credit card numbers are generated following this validity check, commonly known as the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388576018402626):
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.

Now add all single-digit numbers from Step 1.
Add all digits in the odd places from right to left in the card number.

Sum the results from Step 2 and Step 3.

If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid.

Write a program that prompts the user to enter a credit card number as a long integer. Display whether the number is valid or invalid.
Design your program to use the following methods:

public static boolean isValid(long number)

public static int sumOfDoubleEvenPlace(long number)

public static int getDigit(int number)

public static int sumOfOddPlace(long number)

public static boolean prefixMatched(long number, int d)

public static int getSize(long d)

public static long getPrefix(long number, int k)

Here are sample runs of the program: (You may also implement this program by reading the input as a string and processing the string to validate the credit card.)

Enter a credit card number as a long integer: 4388576018410707
4388576018410707 is valid

Enter a credit card number as a long integer: 4388576018402626
4388576018402626 is invalid

下面是参考答案代码:

import java.util.Scanner;

public class Ans6_31_page203 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a credit card number as a long integer:");
        long number = input.nextLong();
        if (isVa1id(number) && divide(number))
            System.out.println(number + " is valid");
        else
            System.out.println(number + " is invalid");
        }

    // Step 0
    public static boolean isVa1id(long number) {
        if (prefixMatched(number,4) || prefixMatched(number,5) ||
                prefixMatched(number,37) || prefixMatched(number,6)) {
            return (number + "").length() >= 13 && (number + "").length() <= 16;
        }
        else
            return false;
    }

    // Get the result from Step 2
    public static int getEven(long number) {
        int getEven = 0;
        for (int i = 0; i < (number+"").length(); i+=2) {
            char n = (number + "").charAt(i);
            int num = Integer.parseInt(Character.toString(n));
            if (num * 2 > 9)
                num = (num * 2 / 10) + (num * 2 % 10);
            else if (num * 2 < 10)
                num = num * 2;
            getEven += num;
        }
        return getEven;
    }

    // Get the result from Step 3
    public static int getOdd(long number) {
        int getOdd = 0;
        for (int i = 1; i < (number+"").length(); i+=2) {
            char n = (number + "").charAt(i);
            int num = Integer.parseInt(Character.toString(n));
            getOdd += num;
        }
        return getOdd;
    }

    // Return sum
    public static int sumOfOddAndEven(long number) {
        return getEven(number) + getOdd(number);
    }

    // Return true if the digit d is a prefix for number
    public static boolean prefixMatched(long number, int d) {
        String strNumber = number + "";
        int charNumber0 = Integer.parseInt(strNumber.substring(0,(d+"").length()));
        return charNumber0 == d;
    }

    public static boolean divide(long d) {
        return sumOfOddAndEven(d) % 10 == 0;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第三十题(游戏:双骰子赌博)(Game: craps) – 编程练习题答案

**6.30(游戏:双骰子赌博)执双骰子游戏是赌场中非常流行的骰子游戏。编写程序,玩这个游戏的一个变种,如下所描述:
执两个骰子。每个骰子有六个面,分别表示值1,2,…,6。检查这两个骰子的和。如果和为2、3或12(称为掷骰子(crap)),你就输了;如果和是7或者11(称作自然(natural)),你就赢了;但如果和是其他数字(例如:4、5、6、8、9或者10),就确定了一个点。继续掷骰子,直到掷出一个7或者掷出和刚才相同的点数。如果掷出的是7,你就输了。如果掷出的点数和你前一次掷出的点数相同,你就赢了。程序扮演一个独立的玩家。

下面是一些运行示例:

You rolled 5 + 6 = 11

You win

You rolled 1 + 2 = 3

You lose

You rolled 4 + 4 = 8

point is 8

You rolled 6 + 2 = 8

You win

You rolled 3 + 2 = 5

point is 5

You rolled 2 + 5 = 7

You lose

**6.30(Game: craps)Craps is a popular dice game played in casinos. Write a program to play a variation of the game, as follows:Roll two dice. Each die has six faces representing values 1, 2, . . ., and 6, respectively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called craps), you lose; if the sum is 7 or 11 (called natural), you win; if the sum is another value (i.e., 4, 5, 6, 8, 9, or 10), a point is established. Continue to roll the dice until either a 7 or the same point value is rolled. If 7 is rolled, you lose. Otherwise, you win. Your program acts as a single player.

Here are some sample runs.

You rolled 5 + 6 = 11

You win

You rolled 1 + 2 = 3

You lose

You rolled 4 + 4 = 8

point is 8

You rolled 6 + 2 = 8

You win

You rolled 3 + 2 = 5

point is 5

You rolled 2 + 5 = 7

You lose

下面是参考答案代码:

public class Ans6_30_page203 {
    public static void main(String[] args) {
        int guessOne = random(6);
        int guessTwo = random(6);
        int guessThree = 0;
        int sum = guessOne + guessTwo;
        int guessTemp = 0;
        boolean nextGuess = true;

        System.out.println("You rolled "+ guessOne +" + "+ guessTwo + " = "+sum);
        if (sum == 7 || sum == 11)
            System.out.println("You win");
        else if (sum == 2 || sum == 3 || sum == 12)
            System.out.println("You lose");
        else {
            while (nextGuess) {
                System.out.println("point is "+sum);
                guessThree = random(6);
                if (guessThree == 7) {
                    System.out.println("You rolled 7 + "+guessThree+" = "+(guessThree*2));
                    System.out.println("You win");
                    nextGuess = false;
                } else if (guessThree == guessOne  || guessThree == guessTwo || guessThree
                == guessTemp) {
                    System.out.println("You rolled "+guessThree+" + "+guessThree+" = "+(guessThree*2));
                    System.out.println("You win");
                    nextGuess = false;
                }else {
                    System.out.println("You rolled "+guessThree+" + "+sum+" = "+(guessThree+sum));
                    System.out.println("You lose");
                    break;
                }
                guessTemp = guessThree;
            }
        }
    }
    public static int random(int guess) {
        return 1 + (int)(Math.random()*guess+1);
    }

}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十九题(双素数)(Twin primes) – 编程练习题答案

**6.29(双素数)双素数是指一对差值为2的素数。例如:3和5就是一对双素数,5和7是一对双素数,而11和13也是一对双素数。编写程序,找出小于1000的所有双素数。如下所示显示结果:

(3,5)

(5,7)

**6.29(Twin primes)(Twin primes) Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and 7 are twin primes, and 11 and 13 are twin primes. Write a program to find all twin primes less than 1,200. Display the output as follows:

(3,5)

(5,7)

下面是参考答案代码:

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

    public static boolean isPrime(double number) {
        boolean isPrime = true;
        for (int divisor = 2; divisor <= number / 2; divisor++) {
            if (number % divisor == 0) {
                isPrime = false;
                break;
            }
        }
        return isPrime;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十八题(梅森素数)(Mersenne prime) – 编程练习题答案

**6.28(梅森素数)如果一个素数可以写成的形式,其中p是某个正整数,那么这个素数就称作梅森素数。编写程序,找出p31的所有梅森素数,然后如下显示输入结果:

**6.28(Mersenne prime) A prime number is called a Mersenne prime if it can be written in the form  for some positive integer p. Write a program that finds all Mersenne primes with p  31 and displays the output as follows:

下面是参考答案代码:

public class Ans6_28_page203 {
    public static void main(String[] args) {
        System.out.printf("%-15s%5s%s", "p", "2^p-1", "\n--------------------\n");

        double masonPrime;
        for (int p = 2; p <= 31; p++) {
            masonPrime = Math.pow(2,p)-1;
            if (isPrime(masonPrime))
                System.out.printf("%-15d%1.0f\n",p,masonPrime);
        }
    }

    public static boolean isPrime(double number) {
        boolean isPrime = true;
        for (int divisor = 2; divisor <= number / 2; divisor++) {
            if (number % divisor == 0) {
                isPrime = false;
                break;
            }
        }
    return isPrime;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十七题(反素数)(Emirp) – 编程练习题答案

**6.27(反素数)反素数(反转拼写的素数)是指一个非回文素数,将其反转之后也是一个素数。例如:17是一个素数,而31也是一个素数,所以17和71是反素数。编写程序,显示前100个反素数。每行显示10个,并且数字间用空格隔开,如下所示:

13 17 31 37 71 73 79 97 107 113

149 157 167 179 199 311 337 347 359 389

**6.27(Emirp)An emirp (prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps. Write a program that displays the first 120 emirps. Display 10 numbers per line, separated by exactly one space, as follows:

13 17 31 37 71 73 79 97 107 113

149 157 167 179 199 311 337 347 359 389

下面是参考答案代码:

public class Ans6_27_page202 {
    public static void main(String[] args) {
        ReverseePrime(100,10);
    }
    public static void ReverseePrime(int n, int 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 "+n+" numbers are \n");

        // Repeatedly find prime numbers
        while (count < n) {
            String strNumber = number+"";
            // Assume the number is prime
            boolean isPrime = true; // Is the current number prime?

            // Test if number is prime
            for (int divisor = 2; divisor <= number / 2; divisor++) {
                if (number % divisor == 0) { // If true, number is not prime
                    isPrime = false; // Set isPrime to false
                    break; // Exit the for loop
                }
            }

            // Test if number is palindrome
            boolean isPalindrome = true;
            //String strNumber = number+"";
            int low = 0;
            int high = strNumber.length() - 1;
            while (low < high) {
                if (strNumber.charAt(low) != strNumber.charAt(high)) {
                    isPalindrome = false;
                    break;
                }
                low++;
                high--;
            }

            // reverseNumber
            int tempNumber = number;
            String strReverseNumber = "";
            while (tempNumber != 0) {
                strReverseNumber += tempNumber % 10;
                tempNumber /=10;
            }
            int reverseNumber = Integer.parseInt(strReverseNumber);
            // ReverseePrime
            boolean isReverseePrime = true;
            for (int divisor = 2; divisor <= reverseNumber / 2; divisor++) {
                if (reverseNumber % divisor == 0) {
                    isReverseePrime = false;
                    break;
                }
            }

            // Print the prime number and increase the count
            if (isPrime && !isPalindrome && isReverseePrime) {
                count++; // Increase the count

                if (count % line == 0) {
                    // Print the number and advance to the new line
                    System.out.println(number);
                }
                else
                    System.out.print(number + " ");
            }

            // Check if the next number is prime
            number++;
        }
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十六题(回文素数)(Palindromic prime) – 编程练习题答案

**6.26(回文素数)回文素数是指一个数同时为素数和回文数。例如:131是一个素数,同时也是一个回文素数。数学313和757也是如此。编写程序,显示前100个回文素数。每行显示10个数,数字中间用一个空格隔开。如下所示:

2 3 5 7 11 101 131 151 181 191

313 353 373 383 727 757 787 797 919 929

**6.26(Palindromic prime) A palindromic prime is a prime number and also palindromic. For example, 131 is a prime and also a palindromic prime, as are 313 and 757. Write a program that displays the first 120 palindromic prime numbers. Display 10 numbers per line, separated by exactly one space, as follows:

2 3 5 7 11 101 131 151 181 191

313 353 373 383 727 757 787 797 919 929

下面是参考答案代码:

public class Ans6_26_page202 {
    public static void main(String[] args) {
        isPrime(100,10);
    }
    public static void isPrime(int n, int 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 "+n+" numbers are \n");

        // Repeatedly find prime numbers
        while (count < n) {
            // Assume the number is prime
            boolean isPrime = true; // Is the current number prime?

            // Test if number is prime
            for (int divisor = 2; divisor <= number / 2; divisor++) {
                if (number % divisor == 0) { // If true, number is not prime
                    isPrime = false; // Set isPrime to false
                    break; // Exit the for loop
                }
            }

            // Test if number is palindrome
            boolean isPalindrome = true;
            String strNumber = number+"";
            int low = 0;
            int high = strNumber.length() - 1;
            while (low < high) {
                if (strNumber.charAt(low) != strNumber.charAt(high)) {
                    isPalindrome = false;
                    break;
                }
                low++;
                high--;
            }

            // Print the prime number and increase the count
            if (isPrime && isPalindrome) {
                count++; // Increase the count

                if (count % line == 0) {
                    // Print the number and advance to the new line
                    System.out.println(number);
                }
                else
                    System.out.print(number + " ");
            }

            // Check if the next number is prime
            number++;
        }
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)

第六章第二十五题(将毫秒数转换成小时数、分钟数和秒数)(Convert milliseconds to hours, minutes, and seconds) – 编程练习题答案

**6.25(将毫秒数转换成小时数、分钟数和秒数)使用下面的方法头,编写一个将毫秒数转换成小时数、分钟数和秒数的方法。

public static String convertMillis(long millis)

该方法返回形如“小时:分钟:秒”的字符串。例如:convertMillis(5500)返回字符串0:0:5,convertMillis(100000)返回字符串0:1:40,convertMillis(555550000)返回字符串154:19:10。编写一个测试程序,提示用户输入一个long型的毫秒数,以“小时:分钟:秒”的格式显示一个字符串。

**6.25(Convert milliseconds to hours, minutes, and seconds)Write a method that converts milliseconds to hours, minutes, and seconds using the following header:

public static String convertMillis(long millis)

The method returns a string as hours:minutes:seconds. For example, convertMillis(5500) returns a string 0:0:5, convertMillis(100000)returns a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10. Write a test program that prompts the user to enter a long integer for milliseconds and displays a string in the format of hours:minutes:seconds.

下面是参考答案代码:

public class Ans6_25_page202 {
    public static void main(String[] args) {
        System.out.println(convertMillis(555550000));
        System.out.println(convertMillis(100000));
        System.out.println(convertMillis(5500));
    }
    public static String convertMillis(long millis) {
        long totalSecond = millis / 1000;
        long currentSecond = totalSecond % 60;
        long totalMinute = totalSecond / 60;
        long currentMinute = totalMinute % 60;
        long totalHour = totalMinute / 60;
        return totalHour+":"+currentMinute+":"+currentSecond;
    }
}

适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)