欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-02 11:57:22
...

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

心血来潮补一下之前没做完的课后题,争取全部做完,欢迎大家评论指正。

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

** 需要书籍或者相关资料可以私聊!!!**

4-1 几何:五边形的面积

import java.util.Scanner;

public class Program4_1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter the length from the center to a vertex:");
		double r = input.nextDouble();
		
		double s = 2 * r * Math.sin(Math.PI/5.0);
		
		double area = 5 * s * s / (4 * Math.tan(Math.PI/5));
		
		System.out.printf("The area of the pentagon is %.2f\n",area);
	}

}

4-2 几何:最大圆距离

import java.util.Scanner;

public class Program4_2 {

   public static void main(String[] args) {
       final double R = 6371.01;

       Scanner input = new Scanner(System.in);

       System.out.print("Enter point 1 (latitude and longitude) in degrees: ");
       double x1 = Math.toRadians(input.nextDouble());
       double y1 = Math.toRadians(input.nextDouble());

       System.out.print("Enter point 2 (latitude and longitude) in degrees: ");
       double x2 = Math.toRadians(input.nextDouble());
       double y2 = Math.toRadians(input.nextDouble());

       double d = R * Math.acos(Math.sin(x1) * Math.sin(x2) + Math.cos(x1) * Math.cos(x2) * Math.cos(y1 - y2));
       System.out.println("The distance between the two points is " + d + " km");
   }

}

4-3 几何:估算面积

public class Program4_3 {

    public static void main(String[] args) {
        final double R = 6371.01;

        double x1 = Math.toRadians(33.78);
        double y1 = Math.toRadians(-84.34);

        double x2 = Math.toRadians(28.57);
        double y2 = Math.toRadians(-81.37);

        double x3 = Math.toRadians(32.04);
        double y3 = Math.toRadians(-81.08);

        double x4 = Math.toRadians(35.20);
        double y4 = Math.toRadians(-80.83);

        double d1 = R * Math.acos(Math.sin(x1) * Math.sin(x2) + Math.cos(x1) * Math.cos(x2) * Math.cos(y1 - y2));
        double d2 = R * Math.acos(Math.sin(x2) * Math.sin(x3) + Math.cos(x2) * Math.cos(x3) * Math.cos(y2 - y3));
        double d3 = R * Math.acos(Math.sin(x1) * Math.sin(x3) + Math.cos(x1) * Math.cos(x3) * Math.cos(y1 - y3));
        double s1 = (d1 + d2 + d3) / 2.0;
        double area1 = Math.pow(s1 * (s1 - d1) * (s1 - d2) * (s1 - d3), 0.5);

        double d4 = R * Math.acos(Math.sin(x1) * Math.sin(x4) + Math.cos(x1) * Math.cos(x4) * Math.cos(y1 - y4));
        double d5 = R * Math.acos(Math.sin(x4) * Math.sin(x3) + Math.cos(x4) * Math.cos(x3) * Math.cos(y4 - y3));
        double d6 = d3;
        double s2 = (d4 + d5 + d6) / 2.0;
        double area2 = Math.pow(s2 * (s2 - d4) * (s2 - d5) * (s2 - d6), 0.5);

        System.out.println("The area of four country is " + (area1 + area2));
    }

}

4-4 几何:六边形面积

import java.util.Scanner;

public class Program4_4 {

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

        System.out.print("Enter the side: ");
        double s = input.nextDouble();

        double area = 6 * s * s / (4 * Math.tan(Math.PI / 6.0));
        System.out.printf("The area of the hexagon is %.2f\n", area);
    }

}

4-5 几何:正多边形的面积

import java.util.Scanner;

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

4-6 圆上的随机点

public class Program4_6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		double m = (double)(Math.toRadians((int)(Math.random() * 360)));
		double aX = Math.round(40 * Math.cos(m) * 100) / 100.00;
		double aY = Math.round(40 * Math.sin(m) * 100) / 100.00;
		
		m = (double)(Math.toRadians((int)(Math.random() * 360)));
		double bX = Math.round(40 * Math.cos(m) * 100) / 100.00;
		double bY = Math.round(40 * Math.sin(m) * 100) / 100.00;
		
		m = (double)(Math.toRadians((int)(Math.random() * 360)));
		double cX = Math.round(40 * Math.cos(m) * 100) / 100.00;
		double cY = Math.round(40 * Math.sin(m) * 100) / 100.00;
		
		double a = Math.sqrt((cX - bX) * (cX - bX) + (cY - bY) * (cY - bY));
		double b = Math.sqrt((cX - aX) * (cX - aX) + (cY - aY) * (cY - aY));
		double c = Math.sqrt((bX - aX) * (bX - aX) + (bY - aY) * (bY - aY));
		
		double A = Math.toDegrees(Math.acos((a*a - b*b - c*c) / (-2 * b * c)));
		double B = Math.toDegrees(Math.acos((b*b - a*a - c*c) / (-2 * a * c)));
		double C = Math.toDegrees(Math.acos((c*c - a*a - b*b) / (-2 * a * b)));
		
		System.out.println("(" + aX + ", " + aY + ")");
		System.out.println("(" + bX + ", " + bY + ")");
		System.out.println("(" + cX + ", " + cY + ")");
		System.out.println( a );
		System.out.println( b );
		System.out.println( c );
		System.out.println("The three angles are " + Math.round(A * 100) / 100.00 + ", " +
				Math.round(B * 100) / 100.00 + ", " + Math.round(C * 100) / 100.00);
	}

}

4-7 顶点坐标

import java.util.Scanner;

public class Program4_7 {

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

        System.out.print("Enter the radius of the bounding circle: ");
        double radius = input.nextDouble();

        System.out.println("The coordinates of five points on the pentagon are: ");
        double a = Math.PI / 2.0;
        for(int i = 1; i <= 5; i++){
            System.out.printf("(%.4f, %.4f)\n", radius * Math.cos(a), radius * Math.sin(a));
            a += Math.toRadians(360 / 5);
        }
    }

}

4-8 给出ASCLL码对应的字符

import java.util.Scanner;

public class Program4_8 {

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

        System.out.print("Enter an ASCLL code: ");
        int a = input.nextInt();

        System.out.printf("The character for ASCLL code %d is %c\n", a, a);
    }

}

4-9 给出字符的Unicode码

import java.util.Scanner;

public class Program4_9 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a character: ");
		String s = input.nextLine();
		char a = s.charAt(0);

		System.out.printf("The Unicode for the character %c is %d\n", a, (int)a);
	}

}

4-10 猜测生日

import java.util.Scanner;

public class Program4_10 {
    public static void main(String[] args) {
        String set1 =
                " 1  3  5  7\n" +
                        " 9 11 13 15\n" +
                        "17 19 21 23\n" +
                        "25 27 29 31";

        String set2 =
                " 2  3  6  7\n" +
                        "10 11 14 15\n" +
                        "18 19 22 23\n" +
                        "26 27 30 31";

        String set3 =
                " 4  5  6  7\n" +
                        "12 13 14 15\n" +
                        "20 21 22 23\n" +
                        "28 29 30 31";

        String set4 =
                " 8  9 10 11\n" +
                        "12 13 14 15\n" +
                        "24 25 26 27\n" +
                        "28 29 30 31";

        String set5 =
                "16 17 18 19\n" +
                        "20 21 22 23\n" +
                        "24 25 26 27\n" +
                        "28 29 30 31";

        int day = 0;

        // Create a Scanner
        Scanner input = new Scanner(System.in);

        // Prompt the user to answer questions
        System.out.print("Is your birthday in Set1?\n");
        System.out.print(set1);
        System.out.print("\nEnter N for No and Y for Yes: ");
        char answer = input.next().charAt(0);

        if (answer == 'Y')
            day += 1;

        // Prompt the user to answer questions
        System.out.print("\nIs your birthday in Set2?\n");
        System.out.print(set2);
        System.out.print("\nEnter 0 for No and 1 for Yes: ");
        answer = input.next().charAt(0);

        if (answer == 'Y')
            day += 2;

        // Prompt the user to answer questions
        System.out.print("Is your birthday in Set3?\n");
        System.out.print(set3);
        System.out.print("\nEnter 0 for No and 1 for Yes: ");
        answer = input.next().charAt(0);

        if (answer == 'Y')
            day += 4;

        // Prompt the user to answer questions
        System.out.print("\nIs your birthday in Set4?\n");
        System.out.print(set4);
        System.out.print("\nEnter 0 for No and 1 for Yes: ");
        answer = input.next().charAt(0);

        if (answer == 'Y')
            day += 8;

        // Prompt the user to answer questions
        System.out.print("\nIs your birthday in Set5?\n");
        System.out.print(set5);
        System.out.print("\nEnter 0 for No and 1 for Yes: ");
        answer = input.next().charAt(0);

        if (answer == 'Y')
            day += 16;

        System.out.println("\nYour birthday is " + day + "!");
    }
}

4-11 十进制转十六进制

import java.util.Scanner;

public class Program4_11 {
	
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a decimal value (0 to 15): ");
		int a = input.nextInt();
		
		if(a <= 15 && a >= 0){
			if(a <= 9)
				System.out.println("The hex value is " + a);
			else
				System.out.println("The hex value is " + (char)(a-10+'A'));
		}
		else
			System.out.println(a + " is an invalid input");
		
	}
}

4-12 十六进制转二进制

import java.util.Scanner;

public class Program4_12 {

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

        System.out.print("Enter a hex digit: ");
        String s = input.next();

        char c = s.charAt(0);
        if(s.length() == 1 && (Character.isDigit(c) || (c >= 'A' && c <= 'F'))){
            int num;
            if(Character.isLetter(c))
                num = 10 + c - 'A';
            else
                num = c - '0';
            String ans = Integer.toBinaryString(num);
            System.out.printf("The binary value is %s\n", ans);
        }else
            System.out.printf("%s is an invalid input\n", s);
    }

}

4-13 判断元音还是辅音

import java.util.Scanner;

public class Program4_13 {

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

        System.out.print("Enter a letter: ");
        String s = input.next();

        char c = s.charAt(0);
        if(s.length() > 1 || !Character.isLetter(c))
            System.out.println(s + " is an invalid input");
        else{
            char m = Character.toLowerCase(c);
            if(m == 'a' || m == 'e' || m == 'i' || m == 'o' || m == 'u')
                System.out.println(c + " is a vowel");
            else
                System.out.println(c + " is a consonant");
        }
    }

}

4-14 转换字母等级为数字

import java.util.Scanner;

public class Program4_14 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a letter grade: ");
		String s = input.nextLine();
		char c = s.charAt(0);
		
		if(s.length() == 1 && Character.isLetter(c)){
			switch (c){
				case 'A':
				case 'B':
				case 'C':
				case 'D':
					System.out.printf("The numeric value for grade %c is %d\n", c, 4 + 'A' - c);
					break;
				case 'F':
					System.out.println("The numeric value for grade F is 0");
					break;
				default:
					System.out.println(s + " is an invalid input");
			}
		}
		else
			System.out.println(s + " is an invalid input");
	}

}

4-15 电话键盘

import java.util.Scanner;

public class Program4_15 {

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

        System.out.print("Enter a letter: ");
        String s = input.next();
        char c = s.charAt(0);
        if(s.length() == 1 && Character.isLetter(c)){
            c = Character.toLowerCase(c);
            int num = 2 + (c - 'a') / 3;
            if(num == 10)    // z or 'Z'
                num--;
            System.out.println("The corresponding number is " + num);
        }else
            System.out.println(s + " is an invalid input");
    }

}

4-16 随机字符

public class Program4_16 {

    public static void main(String[] args) {
        int random = (int)(Math.random() * 26);

        char c = (char) ('A' + random);
        System.out.println("The random character is " + c);
    }

}

4-17 一个月中的日期

import java.util.Scanner;

public class Program4_17 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a year: ");
		int year = input.nextInt();
		
		System.out.print("Enter a month: ");
		String month = input.next();
		
		if(month.equals("Jan") || month.equals("Mar") || month.equals("May") || 
			month.equals("Jul") || month.equals("Aug") || month.equals("Oct") || month.equals("Dem"))
			System.out.println(month + " " + year + " has 31 days");
		else if(month.equals("Apr") || month.equals("Jun") || month.equals("Sep") || month.equals("Nov"))
			System.out.println(month + " " + year + " has 30 days");
		else if(month.equals("Feb")){
			if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
				System.out.println(month + " " + year + " has 29 days");
			else
				System.out.println(month + " " + year + " has 28 days");
		}
	}

}

4-18 学生的专业和状况

import java.util.Scanner;

public class Program4_18 {

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

        System.out.print("Enter two characters: ");
        String s = input.next();
        char c1 = s.charAt(0), c2 = s.charAt(1);

        if(s.length() == 2){
            if((c1 == 'M' || c1 == 'C' || c1 == 'I') && c2 >= '1' && c2 <= '4'){
                if(c1 == 'M')
                    System.out.print("Mathematics ");
                else if(c1 == 'C')
                    System.out.print("Computer Science ");
                else
                    System.out.print("Information Technology ");
                switch (c2){
                    case '1':
                        System.out.println("Freshman");
                        break;
                    case '2':
                        System.out.println("Sophomore");
                        break;
                    case '3':
                        System.out.println("Junior");
                        break;
                    case '4':
                        System.out.println("Senior");
                        break;
                }
            }else
                System.out.println("Invalid input");
        }else
            System.out.println("Invalid input");
    }

}

4-19 商业:检测ISBN-10

import java.util.Scanner;

public class Program4_19 {

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

        System.out.print("Enter the first 9 digits of an ISBN as integer: ");
        String s = input.next();

        int d10 = ((s.charAt(0) - '0') + (s.charAt(1) - '0')*2 + (s.charAt(2) - '0')*3 + (s.charAt(3) - '0')*4
                + (s.charAt(4) - '0')*5 + (s.charAt(5) - '0')*6 + (s.charAt(6) - '0')*7 + (s.charAt(7) - '0')*8
                + (s.charAt(8) - '0')*9) % 11;
        if(d10 == 10)
            System.out.println("The ISBN-10 number is " + s + "X");
        else
            System.out.println("The ISBN-10 number is " + s + d10);
    }

}

4-20 字符串处理

import java.util.Scanner;

public class Program4_20 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		System.out.print("Please enter a string :");
		String str = input.next();
		char a = str.charAt(0);
		int len = str.length();
		
		System.out.println("The first letter of the string is " + a);
		System.out.println("The length of the string is " + len);
	}

}

4-21 检查SSN

import java.util.Scanner;

public class Program4_21 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a SSN: ");
		String ssn = input.next();
		
		boolean flag = true;
		int len = ssn.length();
		if(len != 11)
			flag = false;
		else{
			if(Character.isDigit(ssn.charAt(0)) && Character.isDigit(ssn.charAt(1))
				&& Character.isDigit(ssn.charAt(2)) && Character.isDigit(ssn.charAt(4)) 
				&& Character.isDigit(ssn.charAt(5)) && Character.isDigit(ssn.charAt(7))
				&& Character.isDigit(ssn.charAt(8)) && Character.isDigit(ssn.charAt(9))
				&& Character.isDigit(ssn.charAt(10)) && ssn.charAt(3) == '-' && ssn.charAt(6) == '-')
				flag = true;
			else flag = false;
		}
		if(flag == true)
			System.out.println(ssn + " is a valid social security number");
		else
			System.out.println(ssn + " is an invalid social security number");
	}
}

4-22 检测子串

import java.util.Scanner;

public class Program4_22 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter string s1: ");
		String s1 = input.nextLine();
		
		System.out.print("Enter string s2: ");
		String s2 = input.nextLine();
		
		if(s1.indexOf(s2) != -1)
			System.out.println(s2 + " is a substring of " + s1);
		else
			System.out.println(s2 + " is not a substring of " + s1);
	}

}

4-23 财务应用:酬金

import java.util.Scanner;

public class Program4_23 {

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

        System.out.print("Enter employee's name: ");
        String name = input.next();

        System.out.print("Enter number of hours worked in a week: ");
        double hours = Double.parseDouble(input.next());

        System.out.print("Enter hourly pay rate: ");
        double pay = Double.parseDouble(input.next());

        System.out.print("Enter federal tax withholding rate: ");
        double federal = Double.parseDouble(input.next());

        System.out.print("Enter state tax withholding rate: ");
        double state = Double.parseDouble(input.next());

        System.out.println("Employee Name: %" + name);
        System.out.println("Hours Worked: " +  hours);
        System.out.println("Pay Rate: $" + pay);
        System.out.println("Gross Pay: $" + pay * hours);
        System.out.println("Deduction:");
        System.out.println("  Federal Withholding (" + federal*100 + "%): $" + pay * hours * federal);
        System.out.println("  State Withholding (" + state*100 + "%): $" + pay * hours * state);
        System.out.println("  Total Deduction: $" + (pay * hours * federal + pay * hours * state));
        System.out.println("Net Pay: $" + (pay * hours - pay * hours * federal - pay * hours * state));
    }

}

4-24 对三个城市排序

import java.util.Scanner;

public class Program4_24 {

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

        System.out.print("Enter the first city: ");
        String s1 = input.nextLine();

        System.out.print("Enter the second city: ");
        String s2 = input.nextLine();

        System.out.print("Enter the third city: ");
        String s3 = input.nextLine();

        if(s1.compareTo(s2) > 0){
            String temp = s1;
            s1 = s2;
            s2 = temp;
        }
        if(s2.compareTo(s3) > 0){
            String temp = s2;
            s2 = s3;
            s3 = temp;
        }
        if(s1.compareTo(s2) > 0){
            String temp = s1;
            s1 = s2;
            s2 = temp;
        }

        System.out.println("The three cities in alphabetical order are " + s1 + " " + s2 + " " + s3);
    }

}

4-25 生成车牌号码

public class Program4_25 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int i;
		
		for(i = 0; i < 3;i++) {
			char a;
			a = (char) (Math.random()*26 + 'A');
			System.out.print(a);
		}
		for(int j = 0;j < 4;j++) {
			int b = (int) (Math.random()*10);
			System.out.print(b);
		}
	}

}

4-26 财务应用:货币单位

import java.util.Scanner;

public class Program4_26 {

    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);

        // Receive the amount
        System.out.print("Enter an amount in double, for example 11.56: ");

        String amount = input.next();

        int index  = amount.indexOf('.');
        int remainingAmount = (int)(Integer.parseInt(amount.substring(0, index)) * 100
                + Integer.parseInt(amount.substring(index + 1)));

        // Find the number of one dollars
        int numberOfOneDollars = remainingAmount / 100;
        remainingAmount = remainingAmount % 100;

        // Find the number of quarters in the remaining amount
        int numberOfQuarters = remainingAmount / 25;
        remainingAmount = remainingAmount % 25;

        // Find the number of dimes in the remaining amount
        int numberOfDimes = remainingAmount / 10;
        remainingAmount = remainingAmount % 10;

        // Find the number of nickels in the remaining amount
        int numberOfNickels = remainingAmount / 5;
        remainingAmount = remainingAmount % 5;

        // Find the number of pennies in the remaining amount
        int numberOfPennies = remainingAmount;

        // Display results
        System.out.println("Your amount " + amount + " consists of");
        System.out.println("    " + numberOfOneDollars + " dollars");
        System.out.println("    " + numberOfQuarters + " quarters ");
        System.out.println("    " + numberOfDimes + " dimes");
        System.out.println("    " + numberOfNickels + " nickels");
        System.out.println("    " + numberOfPennies + " pennies");
    }

}
相关标签: java