第六章第三十九题(几何:点的位置)(Geometry: point position) – 编程练习题答案

6.39(几何:点的位置)编程练习题3.32显示如何测试一个点是否在一个有向直线的左侧、右侧,或在该直线上。使用下面的方法头编写该方法:

public static boolean leftOfTheLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheSameLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheLineSegment(double x0, double y0, double x1, double y1, double x2, double y2)

编写一个程序,提示用户输入三个点赋给p0、p1和p2,显示p2是否在从p0到p1的直线的左侧、右侧、直线上,或者线段上。

下面是一些运行示例:

Enter three points for p0, p1, and p2: 1 1 2 2 1.5 1.5

(1.5, 1.5) is on the line segment from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 3 3

(3.0, 3.0) is on the same line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 1.5

(1.0, 1.5) is on the left side of the line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 –1

(1.0, −1.0) is on the right side of the line from (1.0, 1.0) to (2.0, 2.0)

6.39(Geometry: point position) Programming Exercise 3.32 shows how to test whether a point is on the left side of a directed line, on the right, or on the same line. Write the methods with the following headers:

public static boolean leftOfTheLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheSameLine(double x0, double y0, double x1, double y1, double x2, double y2)

public static boolean onTheLineSegment(double x0, double y0, double x1, double y1, double x2, double y2)

Write a program that prompts the user to enter the three points for p0, p1, and p2and displays whether p2 is on the left side of the line from p0 to p1, right side, the same line, or on the line segment.

Here are some sample runs:

Enter three points for p0, p1, and p2: 1 1 2 2 1.5 1.5

(1.5, 1.5) is on the line segment from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 3 3

(3.0, 3.0) is on the same line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 1.5

(1.0, 1.5) is on the left side of the line from (1.0, 1.0) to (2.0, 2.0)

Enter three points for p0, p1, and p2: 1 1 2 2 1 –1

(1.0, −1.0) is on the right side of the line from (1.0, 1.0) to (2.0, 2.0)

下面是参考答案代码:

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

public class Ans6_39_page205 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three points for p0, p1, and p2:");
        double x0 = input.nextDouble();
        double y0 = input.nextDouble();
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();

        if (onTheSameLine(x0, y0, x1, y1, x2, y2)) {
            if (onTheLineSegment(x0, y0, x1, y1, x2, y2)) {
                System.out.printf("(%.1f, %.1f) is on the line segment from "
                        + "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
            } else {
                System.out.printf("(%.1f, %.1f) is on the same line from "
                        + "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
            }
        } else {
            if (leftOfTheLine(x0, y0, x1, y1, x2, y2)) {
                System.out.printf("(%.1f, %.1f) is on the left side of the line from "
                        + "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
            } else {
                System.out.printf("(%.1f, %.1f) is on the right side of the line from "
                        + "(%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1);
            }
        }
    }

    public static boolean leftOfTheLine(double x0, double y0,
                                        double x1, double y1, double x2, double y2) {
        if ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) > 0)
            return true;
        else
            return false;
    }

    public static boolean onTheSameLine(double x0, double y0,
                                        double x1, double y1, double x2, double y2) {
        return (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) == 0;
    }

    public static boolean onTheLineSegment(double x0, double y0,
                                           double x1, double y1, double x2, double y2) {
        if ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) == 0 &&
                x2 <= (Math.max(x0, x1)) && x2 >= (Math.min(x1, x0)))
            return true;
        else
            return false;
    }
}

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

第六章第三十八题(生成随机字符)(Generate random characters) – 编程练习题答案

*6.38(生成随机字符)使用程序清单6-10RandomCharacter中的方法,打印100个大写字母及100个一位数字,每行打印10个。

*6.38(Generate random characters) Use the methods in RandomCharacter in Listing 6.10 to print 100 uppercase letters and then 100 single digits, printing ten per line.

下面是参考答案代码:

// https://cn.fankuiba.com
public class Ans6_38_page205 {
    public static void main(String[] args) {
        for (int count = 1; count <=100; count++) {
            System.out.print(getRandomUpperCaseLetter()+""+getRandomDigitCharacter());
            if (count * 2 % 10 == 0)
                System.out.println();
        }
    }
    public static char getRandomCharacter(char ch1, char ch2) {
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    /** Generate a random uppercase letter */
    public static char getRandomUpperCaseLetter() {
        return getRandomCharacter('A', 'Z');
    }

    /** Generate a random digit character */
    public static char getRandomDigitCharacter() {
        return getRandomCharacter('0', '9');
    }
}

适用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版)更多内容

第六章第三十六题(几何:正多边形的面积)(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版)更多内容

第六章第三十五题(几何:五边形的面积)(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版)更多内容

第六章第三十四题(打印日历)(Print calendar) – 编程练习题答案

**6.34(打印日历)编程练习题3.21使用Zeller一致性原理来计算某天是星期几。使用Zeller的算法简化程序清单6-12以获得每月开始的第一天是星期几。

**6.34(Print calendar) Programming Exercise 3.21 uses Zeller’s congruence to calculate the day of the week. Simplify Listing 6.12, PrintCalendar.java, using Zeller’s algorithm to get the start day of the month.
下面是参考答案代码:

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

public class Ans6_34_page205 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter full year (e.g., 2012): ");
        int year = input.nextInt();
        System.out.print("What day is January 1, "+year+" ? ");
        int week = input.nextInt();

        int month = 1, day = 0;
        String monthString = "";
        boolean leapYear;

        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0 && year % 3200 != 0) || year % 172800 == 0)
            leapYear = true;
        else
            leapYear = false;

        for (; month <= 12; month++) {
            switch (month) {
                case 1:
                    monthString = "January";
                    break;
                case 2:
                    day += 31;
                    monthString = "February";
                    break;
                case 3:
                    monthString = "March";
                    if (leapYear)
                        day += 29;
                    else
                        day += 28;
                    break;
                case 4:
                    day += 31;
                    monthString = "April";
                    break;
                case 5:
                    day += 30;
                    monthString = "May";
                    break;
                case 6:
                    day += 31;
                    monthString = "June";
                    break;
                case 7:
                    day += 30;
                    monthString = "July";
                    break;
                case 8:
                    day += 31;
                    monthString = "August";
                    break;
                case 9:
                    day += 31;
                    monthString = "September";
                    break;
                case 10:
                    day += 30;
                    monthString = "October";
                    break;
                case 11:
                    day += 31;
                    monthString = "November";
                    break;
                case 12:
                    day += 30;
                    monthString = "December";
            }
            int days = (week + day) % 7;
            System.out.print("\n           " + monthString + " " + year + "\n---------------------------------");
            System.out.printf("\n%-5s%-5s%-5s%-5s%-5s%-5s%-5s\n", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

            for (int n =1;n<=days;n++) {
                System.out.printf("%-5s", "");
            }

            int j = 1;
            if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 ||
                    month == 12) {
                for (; j <= 31; j++) {
                    System.out.printf("%-5d", j);
                    if ((days+j) % 7 == 0)
                        System.out.println();
                }
            }
            else if (month == 2 && leapYear) {
                for (; j <= 29; j++) {
                    System.out.printf("%-5d", j);
                    if ((days+j) % 7 == 0)
                        System.out.println();
                }
            }
            else if (month == 2) {
                for (; j <= 28; j++) {
                    System.out.printf("%-5d", j);
                    if ((days+j) % 7 == 0)
                        System.out.println();
                }
            }
            else {
                for (; j <= 30; j++) {
                    System.out.printf("%-5d", j);
                    if ((days + j) % 7 == 0)
                        System.out.println();
                }
            }
            System.out.print("\n");
            switch (days) {
                case 0:
                    System.out.print("Sun");break;
                case 1:
                    System.out.print("Mon");break;
                case 2:
                    System.out.print("Tue");break;
                case 3:
                    System.out.print("Wed");break;
                case 4:
                    System.out.print("Thu");break;
                case 5:
                    System.out.print("Fri");break;
                case 6:
                    System.out.print("Sat");
            }
            System.out.println(" starts on the first day of "+monthString);
        }
    }
}

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

第六章第三十三题(当前日期和时间)(Current date and time) – 编程练习题答案

**6.33(当前日期和时间)调用System.currentTimeMillis()返回从1970年1月1日0点开始至今为止的毫秒数。编写程序,显示当前日期和时间。
下面是运行示例:

Current date and time is May 16, 2012 10:34:23

**6.33(Current date and time) Invoking System.currentTimeMillis() returns the elapsed time in milliseconds since midnight of January 1, 1970. Write a program that displays the date and time.
Here is a sample run:

Current date and time is May 16, 2012 10:34:23

下面是参考答案代码:

// https://cn.fankuiba.com
public class Ans6_33_page205 {
    public static void main(String[] args) {
        // Obtain the total milliseconds since midnight, Jan 1, 1970
        long totalMilliseconds = System.currentTimeMillis();

        // Obtain the total seconds since midnight, Jan 1, 1970
        long totalSeconds = totalMilliseconds / 1000;

        // Compute the current second in the minute in the hour
        long currentSecond = totalSeconds % 60;

        // Obtain the total minutes
        long totalMinutes = totalSeconds / 60;

        // Compute the current minute in the hour
        long currentMinute = totalMinutes % 60;

        // Obtain the total hours
        long totalHours = totalMinutes / 60;

        // Compute the current hour
        long currentHour = totalHours % 24;

        long totalDays = totalHours / 24;

        int currentYear = 1970;

        while (totalDays >= 365) {
            if (isLeapYear(currentYear))
                totalDays -= 366;
            else
                totalDays -= 365;
            currentYear++;
        }

        int currentMonths = 1;
        while (totalDays >= 28) {
            if (currentMonths == 1 || currentMonths == 3 || currentMonths == 5 || currentMonths == 7
                    || currentMonths == 8 || currentMonths == 10 || currentMonths == 12) {
                totalDays -= 31;
                currentMonths++;
            } else if (currentMonths == 4 || currentMonths == 6 || currentMonths == 9 || currentMonths == 11) {
                totalDays -= 30;
                currentMonths++;
            } else if (isLeapYear(currentYear) && currentMonths == 2) {
                totalDays -= 29;
                currentMonths++;
            } else {
                totalDays -= 28;
                currentMonths++;
            }
        }

        long currentDay;
        if (totalDays == 0)
            currentDay = 1;
        else
            currentDay = totalDays + 1;

        // GMT+8
        if (currentHour+8 >= 24) {
            currentHour = currentHour+8-24;
        }

        // IntMonthToStrMonth
        String strCurrentMonths = "";
        switch (currentMonths) {
            case 1:
                strCurrentMonths = "January";break;
            case 2:
                strCurrentMonths = "February";break;
            case 3:
                strCurrentMonths = "March";break;
            case 4:
                strCurrentMonths = "April";break;
            case 5:
                strCurrentMonths = "May";break;
            case 6:
                strCurrentMonths = "June";break;
            case 7:
                strCurrentMonths = "July";break;
            case 8:
                strCurrentMonths = "August";break;
            case 9:
                strCurrentMonths = "September";break;
            case 10:
                strCurrentMonths = "October";break;
            case 11:
                strCurrentMonths = "November";break;
            case 12:
                strCurrentMonths = "December";
        }

        // Display results
        System.out.println("Current date and time is " + strCurrentMonths
                +" "+currentDay+", "+currentYear+" "+
                currentHour+":"+currentMinute+":"+currentSecond);
    }

    /** Determine if it is a leap year */
    public static boolean isLeapYear(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }
}

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

第六章第三十二题(游戏:赢取双骰子赌博游戏的机会)(Game: chance of winning at craps) – 编程练习题答案

**6.32(游戏:赢取双骰子赌博游戏的机会)修改编程练习题6.30使该程序运行10000次,然后显示赢得游戏的次数

**6.32(Game: chance of winning at craps)Revise Exercise 6.30 to run it 15,000 times and display the number of winning games.

下面是参考答案代码:

// https://cn.fankuiba.com
public class Ans6_32_page205 {
    public static void main(String[] args) {
        int count = 0;
        for (int c = 0; c < 10000; c++) {
            int guessOne = random(6);
            int guessTwo = random(6);
            int guessThree;
            int sum = guessOne + guessTwo;
            int guessTemp = 0;
            boolean nextGuess = true;

            //System.out.println("You rolled " + guessOne + " + " + guessTwo + " = " + sum);
            if (sum == 7 || sum == 11) {
                count = count + 1;
                //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");
                        count++;
                        nextGuess = false;
                    } else if (guessThree == guessOne || guessThree == guessTwo || guessThree
                            == guessTemp) {
                        //System.out.println("You rolled " + guessThree + " + " + guessThree + " = " + (guessThree * 2));
                        //System.out.println("You win");
                        count++;
                        nextGuess = false;
                    } else {
                        //System.out.println("You rolled " + guessThree + " + " + sum + " = " + (guessThree + sum));
                        //System.out.println("You lose");
                        break;
                    }
                    guessTemp = guessThree;
                }
            }
        }
        System.out.println(count);
    }

    public static int random(int guess) {
        return 1 + (int) (Math.random() * guess + 1);
    }
}

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

Java提示错误: 找不到或无法加载主类

C:\Java\IdeaProjects\java>java xxxx
错误: 找不到或无法加载主类 xxxx


检查java在Idea终端中是否可用,如不可用,编辑编译器输出路径:文件→项目结构→模块→路径→输出目录 或 设置→工具→终端→项目设置→环境变量

C:\Java\IdeaProjects\java>java -version
java version "1.8.0_231"
Java(TM) SE Runtime Environment (build 1.8.0_231-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode)


检查java在命令行PowerShell中是否可用,如不可用配置好环境变量

PS C:\Users\XX> java
...
有关详细信息, 请参阅 http://www.oracle.com/technetwork/java/javase/documentation/index.html。
PS C:\Users\XX> java xxxx
错误: 找不到或无法加载主类 xxxx


手动拷贝项目路径下的class文件到C:\Users\XX> 下可正常执行
在各终端下cd到class文件存放路径即可“临时”解决此问题

PS C:\Java\IdeaProjects\java\out\production\first> java Demo
OK