-
JAVA程序设计教程
2013-09-07 21:15:19小课题:程序设计语言的历史.....................................................................................13 第二章基本数据类型 .................................................................... -
Java语言程序设计(基础篇)(原书第10版) 第六章编程练习题
2020-06-02 23:22:07目录6-1 数学:五角数6-2 求一个整数各位数字之和6-3 回文整数6-4 反向显示一个整数6-5 对三个数排序6-6 显示图案6-7 财务应用程序:计算未来投资价值6-8 摄氏度和华氏度之间的转换6-9 英尺和米之间的转换6-10 使用...心血来潮补一下之前没做完的课后题,争取全部做完,欢迎大家评论指正。
目录
- 6-1 数学:五角数
- 6-2 求一个整数各位数字之和
- 6-3 回文整数
- 6-4 反向显示一个整数
- 6-5 对三个数排序
- 6-6 显示图案
- 6-7 财务应用程序:计算未来投资价值
- 6-8 摄氏度和华氏度之间的转换
- 6-9 英尺和米之间的转换
- 6-10 使用isPrime方法
- 6-11 财务应用程序:计算酬金
- 6-12 显示字符
- 6-13 数列求和
- 6-14 估算π
- 6-15 财务应用程序:打印税表
- 6-16 一年的天数
- 6-17 显示0和1构成的矩阵
- 6-18 检测密码
- 6-19 MyTriangle类
- 6-20 计算一个字符串中字母的个数
- 6-21 电话按键盘
- 6-22 数学:平方根的近似求法
- 6-23 指定字符的出现次数
- 6-24 显示当前日期和时间
- 6-25 将毫秒数转换成小时数、分钟数和秒数
- 6-26 回文素数
- 6-27 反素数
- 6-28 梅森素数
- 6-29 双素数
- 6-30 游戏:双骰儿赌博
- 6-31 财务应用程序:信用卡号的合法性
- 6-32 游戏:赢取双骰子赌博游戏的机会
- 6-33 当前曰期和时间
- 6-34 打印日历
- 6-35 几何问题:五边形的面积
- 6-36 几何问题:正多边形的面积
- 6-37 格式化整数
- 6-38 生成随机字符
- 6-39 几何:点的位置
需要书籍或者相关资料可以私聊!!!
6-1 数学:五角数
public class Program6_1 { public static void main(String[] args) { final int NUMBER_PER_LINE = 10; int cnt = 0; for (int i = 1; i <= 100; i++) { System.out.printf("%-7d", getPentagonalNumber(i)); cnt++; if(cnt % NUMBER_PER_LINE == 0) System.out.println(); } } public static int getPentagonalNumber(int n){ return n * (3*n - 1) / 2; } }
6-2 求一个整数各位数字之和
import java.util.Scanner; public class Program6_2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.print("Please enter a number: "); long n = input.nextLong(); System.out.println("The sum of the numbers of this number is " + sumDigits(n)); input.close(); } public static int sumDigits(long n) { int sum = 0; while(n > 0) { sum += n % 10; n /= 10; } return sum; } }
6-3 回文整数
import java.util.Scanner; public class Program6_3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter a number: "); int n = input.nextInt(); if(isPalindrome(n) == true) System.out.println(n + " is a palindrome number"); else System.out.println(n + " is not a palindrome number"); input.close(); } //Return true if number is a palindrome public static boolean isPalindrome(int number) { if(number == reverse(number)) return true; else return false; } //Return the reversal of an integer, i.e., reverse(456) returns 654 public static int reverse(int number) { String str1 = number + ""; String str2 = ""; for(int i = str1.length()-1; i >= 0; i--) str2 += str1.charAt(i); return Integer.parseInt(str2); } }
6-4 反向显示一个整数
import java.util.Scanner; public class Program6_4 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter a number: "); int n = input.nextInt(); reverse(n); input.close(); } public static void reverse(int number) { String str1 = number + ""; String str2 = ""; for(int i = str1.length()-1; i >= 0; i--) str2 += str1.charAt(i); System.out.println("The reverse number of " + number + " is " + str2); } }
6-5 对三个数排序
import java.util.Scanner; public class Program6_5 { public static void main(String[] args) { System.out.print("Enter three numbers to sort: "); Scanner input = new Scanner(System.in); double num1 = input.nextDouble(); double num2 = input.nextDouble(); double num3 = input.nextDouble(); displaySortedNumbers(num1, num2, num3); input.close(); } public static void displaySortedNumbers(double num1, double num2, double num3){ if(num1 > num2){ double temp = num1; num1 = num2; num2 = temp; } if(num2 > num3){ double temp = num2; num2 = num3; num3 = temp; } if(num1 > num2){ double temp = num1; num1 = num2; num2 = temp; } System.out.println("Sorted numbers: " + num1 + " " + num2 + " " + num3); } }
6-6 显示图案
import java.util.Scanner; public class Program6_6 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int n = input.nextInt(); displayPattern(n); input.close(); } public static void displayPattern(int n){ for (int i = 1; i <= n; i++) { for (int j = 1; j <= n - i; j++) System.out.print(" "); for (int j = i; j >= 1; j--) System.out.printf("%-4d", j); System.out.println(); } } }
6-7 财务应用程序:计算未来投资价值
import java.util.Scanner; public class Program6_7 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("The amount invested: "); double investmentAmount = input.nextDouble(); System.out.print("Annual interest rate: "); double rate = input.nextDouble(); System.out.println("Years Future Value"); for (int i = 1; i <= 30; i++) System.out.printf("%-10d%.2f\n", i, futureInvestmentValue(investmentAmount, rate/1200, i)); input.close(); } public static double futureInvestmentValue( double investmentAmount, double monthlyInterestRate, int years){ return investmentAmount * Math.pow(1 + monthlyInterestRate, years * 12); } }
6-8 摄氏度和华氏度之间的转换
public class Program6_8 { public static void main(String[] args) { System.out.println("摄氏度 华氏度 华氏度 摄氏度"); System.out.println("-----------------------------------"); for (double i = 40, j = 120; i >= 31; i--, j -= 10) { System.out.printf("%-9.1f%-13.1f%-9.1f%.2f\n", i, celsiusToFahrenheit(i), j, fahrenheitToCelsius(j)); } } //Convert from Celsius to Fahrenheit public static double celsiusToFahrenheit(double celsius){ return (9.0 / 5) * celsius + 32; } //Convert from Fahrenheit to Celsius public static double fahrenheitToCelsius(double fahrenheit){ return (5.0 / 9) * (fahrenheit - 32); } }
6-9 英尺和米之间的转换
public class Program6_9 { public static void main(String[] args) { System.out.println("英尺 米 米 英尺"); System.out.println("------------------------------------------"); for (double i = 1, j = 20; i <= 10; i++, j += 5) { System.out.printf("%4.1f%10.3f", i, footToMeter(i)); System.out.printf("%14.1f\t%10.3f", j, meterToFoot(j)); System.out.println(); } } //Convert from feet to meters public static double footToMeter(double foot) { return (0.305 * foot); } //Convert from meters to feet public static double meterToFoot(double meter) { return (3.279 * meter); } }
6-10 使用isPrime方法
public class Program6_10 { public static void main(String[] args) { final int MAX_NUMBER = 10000; int cnt = 0; for (int i = 2; i <= MAX_NUMBER; i++) if(isPrime(i)) cnt++; System.out.printf("There are %d prime numbers less than 10000.", cnt); } /** Check whether number is prime */ public static boolean isPrime(int number) { for (int divisor = 2; divisor <= number / 2; divisor++) { if (number % divisor == 0) { // If true, number is not prime return false; // number is not a prime } } return true; // number is prime } }
6-11 财务应用程序:计算酬金
public class Program6_11 { public static void main(String[] args) { System.out.println("销售总额 酬金"); System.out.println("---------------------"); for (int i = 10000; i <= 100000; i += 5000) { System.out.printf("%-10d%10.1f\n", i, computeCommission(i)); } } public static double computeCommission(double saleAmount){ if(saleAmount <= 5000) return saleAmount * 0.08; else if(saleAmount <= 10000) return 5000 * 0.08 + (saleAmount - 5000) * 0.1; else return 5000*0.08 + 5000*0.1 + (saleAmount - 10000) * 0.12; } }
6-12 显示字符
public class Program6_12 { public static void main(String[] args) { printChars('1', 'Z', 10); } public static void printChars(char ch1, char ch2, int numberPerLine){ int cnt = 0; for (char i = ch1; i <= ch2; i++) { System.out.print(i + " "); cnt++; if (cnt % numberPerLine == 0) System.out.println(); } } }
6-13 数列求和
public class Program6_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("%-8d%10.4f\n", i, m(i)); } public static double m(int n) { double sum = 0; for(int i = 1;i <= n; i++) sum += i * 1.0 / (i+1); return sum; } }
6-14 估算π
public class Program6_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("%-10d%10.4f\n",i,m(i)); } public static double m(int i) { double sum = 0; int sign = 1; for(int n = 1; n <= i;n++) { sum += sign * 1.0 / (2 * n - 1); sign = -sign; } return sum * 4; } }
6-15 财务应用程序:打印税表
public class Program6_15 { public static void main(String[] args) { System.out.println("Taxable Income Single Married Joint Married Separate Head of a House"); System.out.println("--------------------------------------------------------------------------------"); for (int i = 50000; i <= 60000; i += 50) { System.out.printf(" %-14d%-13d%-17d%-20d%d\n", i, Math.round(computeTax(0, i)), Math.round(computeTax(1, i)), Math.round(computeTax(2, i)), Math.round(computeTax(3, i))); } } public static double computeTax(int status, double taxableIncome){ double tax = 0; if (status == 0) { // Compute tax for single filers if (taxableIncome <= 8350) tax = taxableIncome * 0.10; else if (taxableIncome <= 33950) tax = 8350 * 0.10 + (taxableIncome - 8350) * 0.15; else if (taxableIncome <= 82250) tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (taxableIncome - 33950) * 0.25; else if (taxableIncome <= 171550) tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (taxableIncome - 82250) * 0.28; else if (taxableIncome <= 372950) tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (taxableIncome - 171550) * 0.33; else tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (taxableIncome - 372950) * 0.35; } else if (status == 1) { // Compute tax for married file jointly if (taxableIncome <= 16700) tax = taxableIncome * 0.10; else if (taxableIncome <= 67900) tax = 16700 * 0.10 + (taxableIncome - 16700) * 0.15; else if (taxableIncome <= 137050) tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (taxableIncome - 67900) * 0.25; else if (taxableIncome <= 208850) tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (taxableIncome - 137050) * 0.28; else if (taxableIncome <= 372950) tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (taxableIncome - 208850) * 0.33; else tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (372950 - 208850) * 0.33 + (taxableIncome - 372950) * 0.35; } else if (status == 2) { // Compute tax for married separately if (taxableIncome <= 8350) tax = taxableIncome * 0.10; else if (taxableIncome <= 33950) tax = 8350 * 0.10 + (taxableIncome - 8350) * 0.15; else if (taxableIncome <= 68525) tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (taxableIncome - 33950) * 0.25; else if (taxableIncome <= 104425) tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (taxableIncome - 68525) * 0.28; else if (taxableIncome <= 186745) tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (taxableIncome - 104425) * 0.33; else tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186745 - 104425) * 0.33 + (taxableIncome - 186745) * 0.35; } else if (status == 3) { // Compute tax for head of household if (taxableIncome <= 11950) tax = taxableIncome * 0.10; else if (taxableIncome <= 45500) tax = 11950 * 0.10 + (taxableIncome - 11950) * 0.15; else if (taxableIncome <= 117450) tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (taxableIncome - 45500) * 0.25; else if (taxableIncome <= 190200) tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (taxableIncome - 117450) * 0.28; else if (taxableIncome <= 372950) tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (taxableIncome - 190200) * 0.33; else tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33 + (taxableIncome - 372950) * 0.35; } return tax; } }
6-16 一年的天数
public class Program6_16 { public static void main(String[] args) { for(int i = 2000; i <= 2020; i++) System.out.println("The number of days in the " + i + " is " + numberOfDaysInAYear(i)); } public static int numberOfDaysInAYear(int year) { if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return 366; else return 365; } }
6-17 显示0和1构成的矩阵
import java.util.Scanner; public class Program6_17 { public static void main(String[] args) { System.out.print("Enter n: "); Scanner input = new Scanner(System.in); printMatrix(input.nextInt()); input.close(); } public static void printMatrix(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print((int) (Math.random() * 2) + " "); System.out.println(); } } }
6-18 检测密码
import java.util.Scanner; public class Program6_18 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.print("Please enter a password: "); String password = input.nextLine(); if(isValidPassword(password)) System.out.println("Valid Passwprd"); else System.out.println("Invalid Password"); } public static boolean isValidPassword(String str) { if(str.length() < 8) return false; int numCount = 0; for(int i = 0; i < str.length(); i++) { char m = str.charAt(i); if(Character.isLetterOrDigit(m)) { if(Character.isDigit(m)) numCount++; } else return false; } if(numCount >= 2) return true; else return false; } }
6-19 MyTriangle类
import java.util.Scanner; public class Program6_19 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter three sides of the triangle: "); double side1 = input.nextDouble(); double side2 = input.nextDouble(); double side3 = input.nextDouble(); if(isValid(side1, side2, side3)) System.out.printf("The area of the triangle is %.2f\n", area(side1, side2, side3)); else System.out.println("Invalid input"); input.close(); } //Return true if the sum of any two sides is greater than the third side public static boolean isValid(double side1, double side2, double side3) { if(side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) return true; return false; } //Return the area of the triangle public static double area(double side1, double side2, double side3){ double s = (side1 + side2 + side3) / 2; return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3)); } }
6-20 计算一个字符串中字母的个数
import java.util.Scanner; public class Program6_20 { public static void main(String[] args) { System.out.print("Enter a string: "); Scanner input = new Scanner(System.in); String s = input.next(); System.out.printf("The letters of %s is %d\n", s, countLetters(s)); } public static int countLetters(String s){ int count = 0; for (int i = 0; i < s.length(); i++) if(Character.isLetter(s.charAt(i))) count++; return count; } }
6-21 电话按键盘
import java.util.Scanner; public class Program6_21 { public static void main(String[] args) { System.out.print("Enter a string: "); Scanner input = new Scanner(System.in); String s = input.next(); for (int i = 0; i < s.length(); i++) if(Character.isLetter(s.charAt(i))) System.out.print(getNumber(Character.toUpperCase(s.charAt(i)))); else System.out.print(s.charAt(i)); System.out.println(); input.close(); } public static int getNumber(char uppercaseLetter){ if(uppercaseLetter <= 'O') return 2 + (uppercaseLetter - 'A') / 3; else if(uppercaseLetter <= 'S') return 7; else if(uppercaseLetter <= 'V') return 8; else return 9; } }
6-22 数学:平方根的近似求法
import java.util.Scanner; public class Program6_22 { public static void main(String[] args) { System.out.print("Enter a number: "); Scanner input = new Scanner(System.in); long n = input.nextLong(); System.out.printf("The sqrt of %d is %.6f\n", n, sqrt(n)); } public static double sqrt(long n){ double lastGuess = 1; double nextGuess = 1; do { lastGuess = nextGuess; nextGuess = (lastGuess + n / lastGuess) / 2; }while(Math.abs(lastGuess - nextGuess) > 1e-6); return nextGuess; } }
6-23 指定字符的出现次数
import java.util.Scanner; public class Program6_23 { public static void main(String[] args) { System.out.print("Enter a string: "); Scanner input = new Scanner(System.in); String str = input.nextLine(); System.out.print("Enter a character: "); char c = input.next().charAt(0); System.out.printf("The character %c appears %d times in %s\n", c, count(str, c), str); } public static int count(String str, char a){ int cnt = 0; for (int i = 0; i < str.length(); i++) { if(a == str.charAt(i)) cnt++; } return cnt; } }
6-24 显示当前日期和时间
public class Program6_24 { public static void main(String[] args) { ShowCurrentTime(); } public static void ShowCurrentTime() { // 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; long days = totalDays; long beijingHour = currentHour + 8; if (beijingHour > 24) { days++; beijingHour %= 24; } int currentYear = 1970; while (days > numberOfDaysInAYear(currentYear)) { days -= numberOfDaysInAYear(currentYear); currentYear++; } int currentMonth = 1; while(true){ if(currentMonth == 1 || currentMonth == 3 || currentMonth == 5 || currentMonth == 7 || currentMonth == 8 || currentMonth == 10 || currentMonth == 12){ if(days <= 31) break; days -= 31; currentMonth++; }else if(currentMonth == 4 || currentMonth == 6 || currentMonth == 9 || currentMonth == 11){ if (days <= 30) break; days -= 30; currentMonth++; }else{ if(isLeap(currentYear)){ if (days <= 29) break; days -= 29; currentMonth++; }else { if (days <= 28) break; days -= 28; currentMonth++; } } } long currentDay = days + 1; // Display results System.out.println("Current date is " + currentYear + "/" + currentMonth + "/" + currentDay + " " + beijingHour + ":" + currentMinute + ":" + currentSecond); } public static int numberOfDaysInAYear(int year) { if (isLeap(year)) return 366; else return 365; } public static boolean isLeap(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } }
6-25 将毫秒数转换成小时数、分钟数和秒数
import java.util.Scanner; public class Program6_25 { public static void main(String[] args) { System.out.print("Enter milliseconds: "); Scanner input = new Scanner(System.in); long millis = input.nextLong(); System.out.println(convertMillis(millis)); input.close(); } public static String convertMillis(long millis){ long second = millis / 1000; long currentSecond = second % 60; long minute = second / 60; long currentMinute = minute % 60; long currentHour = minute / 60; return currentHour + ":" + currentMinute + ":" + currentSecond; } }
6-26 回文素数
public class Program6_26 { public static void main(String[] args) { final int NUMBERS_PER_LINE = 10; int s = 100, count = 0; for (int i = 2; count < s; i++) if (isPalindrome(i) && isPrime(i)) { System.out.print(i); count++; if (count % NUMBERS_PER_LINE == 0) System.out.println(); else System.out.print(" "); } } public static boolean isPalindrome(int number) { if (number == reverse(number)) return true; else return false; } public static int reverse(int number) { String str1 = number + ""; String str2 = ""; for (int i = str1.length() - 1; i >= 0; i--) str2 += str1.charAt(i); return Integer.parseInt(str2); } public static boolean isPrime(int number) { for (int i = 2; i <= Math.sqrt(number); i++) if (number % i == 0) return false; return true; } }
6-27 反素数
public class Program6_27 { public static void main(String[] args) { final int NUMBER_PER_LINE = 10; final int NUMBER = 100; int cnt = 0; for (int i = 2; cnt < NUMBER; i++) { if(!isPalindrome(i) && isPrime(i) && isPrime(reverse(i))){ System.out.print(i + " "); cnt++; if (cnt % NUMBER_PER_LINE == 0) System.out.println(); } } } public static boolean isPalindrome(int number) { if (number == reverse(number)) return true; else return false; } public static int reverse(int number) { String str1 = number + ""; String str2 = ""; for (int i = str1.length() - 1; i >= 0; i--) str2 += str1.charAt(i); return Integer.parseInt(str2); } public static boolean isPrime(int number) { for (int i = 2; i <= Math.sqrt(number); i++) if (number % i == 0) return false; return true; } }
6-28 梅森素数
public class Program6_28 { public static void main(String[] args) { final int MAX_NUMBER = 31; System.out.println("p 2^p-1"); System.out.println("-------------------"); for (int i = 2; i <= MAX_NUMBER; i++) { if(isPrime((1 << i) - 1)) System.out.printf("%-12d%d\n", i, ((1 << i) - 1)); } } public static boolean isPrime(int number) { for (int i = 2; i <= Math.sqrt(number); i++) if (number % i == 0) return false; return true; } }
6-29 双素数
public class Program6_29 { public static void main(String[] args) { final int MAX_NUMBER = 1000; for (int i = 2; i <= MAX_NUMBER - 2; i++) { if(isPrime(i) && isPrime(i+2)) System.out.printf("(%d, %d)\n", i, i+2); } } public static boolean isPrime(int number) { for (int i = 2; i <= Math.sqrt(number); i++) if (number % i == 0) return false; return true; } }
6-30 游戏:双骰儿赌博
public class Program6_30 { public static void main(String[] args) { diceGame(); } public static void diceGame() { int num1 = (int) (Math.random() * 6 + 1); int num2 = (int) (Math.random() * 6 + 1); int sum1 = num1 + num2; int a = 0; System.out.println("You rolled " + num1 + " + " + num2 + " = " + sum1); if(isWin(num1,num2) == 1) System.out.println("You win"); else if(isWin(num1, num2) == 0) System.out.println("You lose"); else { System.out.println("point is " + sum1); while (true) { num1 = (int) (Math.random() * 6 + 1); num2 = (int) (Math.random() * 6 + 1); int sum2 = num1 + num2; System.out.println("You rolled " + num1 + " + " + num2 + " = " + sum2); if (sum2 == sum1) { System.out.println("You win"); break; } else if (sum2 == 7) { System.out.println("You lose"); break; } } } } public static int isWin(int num1, int num2) { int sum = num1 + num2; if(sum == 2 || sum == 3 || sum == 12) return 0; if(sum == 7 || sum == 11) return 1; else return 2; } }
6-31 财务应用程序:信用卡号的合法性
import java.util.Scanner; public class Program6_31 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); //用户输入卡号判断卡号是否有效 System.out.println("Enter a credit card number as a long integer:"); long number = input.nextLong(); if(isValid(number)) System.out.println(number + " is valid"); else System.out.println(number + " is invalid"); } //Return true if the card number is valid public static boolean isValid(long number) { int count = getSize(number); if(count > 16 || count <13) return false; if(!prefixMatched(number,4) && !prefixMatched(number,5) && !prefixMatched(number,6) && !prefixMatched(number,37)) return false; int m = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number); if(m % 10 != 0) return false; return true; } //Get the result from Step2 public static int sumOfDoubleEvenPlace(long number) { int sum = 0; number /= 10; while(number > 0) { sum += getDigit((int) (number % 10) * 2); number /= 100; } return sum; } //Return this number if it is a single digit, otherwise, return the sum of the two digits public static int getDigit(int number) { if(number < 10) return number; else { int a = number % 10, b = number / 10; return (a+b); } } //Return sum of odd-place digits in number public static int sumOfOddPlace(long number) { int sum = 0; while(number > 0) { sum += number % 10; number /= 100; } return sum; } //Return true if the digit d is a prefix for number public static boolean prefixMatched(long number, int d) { int count1 = getSize(number), count2 = getSize(d); number /= Math.pow(10.0, count1 - count2); if(number == d) return true; else return false; } //Return the number of digits in d public static int getSize(long d) { return (d + "").length(); } //Return the first k number of digits from number. // If the number of digits in number is less than k, return number. public static long getPrefix(long number, int k) { int count = getSize(number); if(count <= k) return number; else return (long) (number / (Math.pow(10.0, count - k))); } }
6-32 游戏:赢取双骰子赌博游戏的机会
public class Program6_32 { public static void main(String[] args) { final int TIMES = 10000; int cnt = 0; for (int i = 0; i < TIMES; i++) cnt += diceGame(); System.out.printf("You win %d times out of %d\n", cnt, TIMES); } public static int diceGame() { int num1 = (int) (Math.random() * 6 + 1); int num2 = (int) (Math.random() * 6 + 1); int sum1 = num1 + num2; if(isWin(num1,num2) == 1) return 1; else if(isWin(num1, num2) == 0) return 0; else { while (true) { num1 = (int) (Math.random() * 6 + 1); num2 = (int) (Math.random() * 6 + 1); int sum2 = num1 + num2; if (sum2 == sum1) return 1; else if (sum2 == 7) return 0; } } } public static int isWin(int num1, int num2) { int sum = num1 + num2; if(sum == 2 || sum == 3 || sum == 12) return 0; if(sum == 7 || sum == 11) return 1; else return 2; } }
6-33 当前曰期和时间
public class Program6_33 { public static void main(String[] args) { ShowCurrentTime(); } public static void ShowCurrentTime() { // 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; long days = totalDays; long beijingHour = currentHour + 8; if (beijingHour > 24) { days++; beijingHour %= 24; } int currentYear = 1970; while (days > numberOfDaysInAYear(currentYear)) { days -= numberOfDaysInAYear(currentYear); currentYear++; } int currentMonth = 1; while(true){ if(currentMonth == 1 || currentMonth == 3 || currentMonth == 5 || currentMonth == 7 || currentMonth == 8 || currentMonth == 10 || currentMonth == 12){ if(days <= 31) break; days -= 31; currentMonth++; }else if(currentMonth == 4 || currentMonth == 6 || currentMonth == 9 || currentMonth == 11){ if (days <= 30) break; days -= 30; currentMonth++; }else{ if(isLeap(currentYear)){ if (days <= 29) break; days -= 29; currentMonth++; }else { if (days <= 28) break; days -= 28; currentMonth++; } } } long currentDay = days + 1; String strCurrentMonth = ""; switch (currentMonth){ case 1: strCurrentMonth = "January"; break; case 2: strCurrentMonth = "February"; break; case 3: strCurrentMonth = "March"; break; case 4: strCurrentMonth = "April"; break; case 5: strCurrentMonth = "May"; break; case 6: strCurrentMonth = "June"; break; case 7: strCurrentMonth = "July"; break; case 8: strCurrentMonth = "August"; break; case 9: strCurrentMonth = "September"; break; case 10: strCurrentMonth = "October"; break; case 11: strCurrentMonth = "November"; break; case 12: strCurrentMonth = "December"; break; } // Display results System.out.println("Current date and time is " + strCurrentMonth + " " + currentDay + ", " + currentYear + " " + beijingHour + ":" + currentMinute + ":" + currentSecond); } public static int numberOfDaysInAYear(int year) { if (isLeap(year)) return 366; else return 365; } public static boolean isLeap(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } }
6-34 打印日历
import java.util.Scanner; public class Program6_34 { /** Main method */ public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter year System.out.print("Enter full year (e.g., 2001): "); int year = input.nextInt(); // Prompt the user to enter month System.out.print("Enter month in number between 1 and 12: "); int month = input.nextInt(); // Print calendar for the month of the year printMonth(year, month); input.close(); } /** Print the calendar for a month in a year */ public static void printMonth(int year, int month) { // Print the headings of the calendar printMonthTitle(year, month); // Print the body of the calendar printMonthBody(year, month); } /** Print the month title, e.g., May, 1999 */ public static void printMonthTitle(int year, int month) { System.out.println(" " + getMonthName(month) + " " + year); System.out.println("-----------------------------"); System.out.println(" Sun Mon Tue Wed Thu Fri Sat"); } /** Get the English name for the month */ public static String getMonthName(int month) { String monthName = ""; switch (month) { case 1: monthName = "January"; break; case 2: monthName = "February"; break; case 3: monthName = "March"; break; case 4: monthName = "April"; break; case 5: monthName = "May"; break; case 6: monthName = "June"; break; case 7: monthName = "July"; break; case 8: monthName = "August"; break; case 9: monthName = "September"; break; case 10: monthName = "October"; break; case 11: monthName = "November"; break; case 12: monthName = "December"; } return monthName; } /** Print month body */ public static void printMonthBody(int year, int month) { // Get start day of the week for the first date in the month int startDay = getStartDay(year, month); // Get number of days in the month int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month); // Pad space before the first day of the month int i = 0; for (i = 0; i < startDay; i++) System.out.print(" "); for (i = 1; i <= numberOfDaysInMonth; i++) { System.out.printf("%4d", i); if ((i + startDay) % 7 == 0) System.out.println(); } System.out.println(); } /** Get the start day of month/1/year */ public static int getStartDay(int year, int month) { int m; if(month > 2) m = month; else{ m = month + 12; year--; } int j = year / 100; int k = year % 100; int h = (1 + 26*(m+1)/10 + k + k/4 + j/4 + 5*j) % 7 - 1; return h; } /** Get the total number of days since January 1, 1800 */ public static int getTotalNumberOfDays(int year, int month) { int total = 0; // Get the total days from 1800 to 1/1/year for (int i = 1800; i < year; i++) if (isLeapYear(i)) total = total + 366; else total = total + 365; // Add days from Jan to the month prior to the calendar month for (int i = 1; i < month; i++) total = total + getNumberOfDaysInMonth(year, i); return total; } /** Get the number of days in a month */ public static int getNumberOfDaysInMonth(int year, int month) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) return 31; if (month == 4 || month == 6 || month == 9 || month == 11) return 30; if (month == 2) return isLeapYear(year) ? 29 : 28; return 0; // If month is incorrect } /** Determine if it is a leap year */ public static boolean isLeapYear(int year) { return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0); } }
6-35 几何问题:五边形的面积
import java.util.Scanner; public class Program6_35 { public static void main(String[] args) { System.out.print("Enter the side: "); Scanner input = new Scanner(System.in); 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)); } }
6-36 几何问题:正多边形的面积
import java.util.Scanner; public class Program6_36 { 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 side = input.nextDouble(); System.out.println("The area of the polygon is " + area(n, side)); input.close(); } public static double area(int n, double side) { return (n * side * side) / (4 * Math.tan(Math.PI / n)); } }
6-37 格式化整数
import java.util.Scanner; public class Program6_37 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter a number: "); int number = input.nextInt(); System.out.print("Please enter the width: "); int width = input.nextInt(); String s = format(number, width); System.out.println(s); input.close(); } public static String format(int number, int width) { String s = ""; int count = getSize(number); if(count >= width) s = number + ""; else { for(int i = 1; i <= width - count; i++) s += "0"; s += number + ""; } return s; } public static int getSize(int number) { return (number + "").length(); } }
6-38 生成随机字符
public class Program6_38 { public static void main(String[] args) { final int NUMBET_PER_LINE = 10; final int NUMBER = 100; int cnt = 0; for (int i = 0; i < NUMBER; i++) { System.out.print(getRandomCharacter('A', 'Z') + " "); cnt++; if(cnt % NUMBET_PER_LINE == 0) System.out.println(); } System.out.println(); cnt = 0; for (int i = 0; i < NUMBER; i++) { System.out.print(getRandomCharacter('0', '9') + " "); cnt++; if(cnt % NUMBET_PER_LINE == 0) System.out.println(); } } public static char getRandomCharacter(char ch1, char ch2) { return (char)(ch1 + Math.random() * (ch2 - ch1 + 1)); } }
6-39 几何:点的位置
import java.util.Scanner; public class Program6_39 { 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(leftOnTheLine(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 if(onTheSameLine(x0, y0, x1, y1, x2, y2)) System.out.printf("(%.1f, %.1f) is on the same line " + "from (%.1f, %.1f) to (%.1f, %.1f)", x2, y2, x0, y0, x1, y1); else if(onTheLineSegment(x0, y0, x1, y1, x2, y2)) 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); } //Return true if point (x2, y2) is on the left side of // the directed line from (xO, yO) to (x1, y1) public static boolean leftOnTheLine(double x0, double y0, double x1, double y1, double x2, double y2){ return (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) > 0; } //Return true if point (x2, y2) is on the same //line from (xO, yO) to (x1, y1) 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; } //Return true if point (x2, y2) is on the line segment // from (xO, yO) to (x1, y1) public static boolean onTheLineSegment(double x0, double y0, double x1, double y1, double x2, double y2){ return (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) < 0; } }
-
从Java基础、JavaWeb基础到常用的框架再到面试题都有完整的教程,几乎涵盖了Java后端必备的知识点。该开源仓库的文章都是我个人原创,公众号发过的技术文章(干货)也会有相关的目录整理,很多知识点我还在不停的...
-
程序设计抽象思想:C语言描述.[美]Eric S.Roberts(带详细书签).pdf
2019-03-12 19:32:057.3.4 合并排序的计算复杂度 239 7.3.5 比较N2和NlogN的性能 240 7.4 标准复杂度类型 241 7.5 快速排序算法 242 7.5.1 分割数组 244 7.5.2 分析快速排序的性能 246 7.6 数学归纳法 247 7.7 小结 250 7.8 ... -
java常用工具类的使用
2012-03-19 20:11:37在Java程序设计过程中,对应日期和时间的格式化,还有一个简单的格式化方式,就是java.text.SimpleDateFormat,该类中用字符串指定日期和时间的格式,字符串中的字符称为模式字符,模式字符区分大小写。常见的模式... -
超级有影响力霸气的Java面试题大全文档
2012-07-18 09:47:04超级有影响力的Java面试题大全文档 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节。... -
Java开发技术大全(500个源代码).
2012-12-02 19:55:48HelloNative.java 准备调用C函数的java文件 HelloNative.lib 用VC编译生成的静态库文件 HelloNative.obj 用VB编译生成的目标文件 HelloNativeTest.java 测试本地化是否成功的类文件 instanceVar.java 定义一个... -
JAVA上百实例源码以及开源项目
2016-01-03 17:37:40Tcp服务端与客户端的JAVA实例源代码,一个简单的Java TCP服务器端程序,别外还有一个客户端的程序,两者互相配合可以开发出超多的网络程序,这是最基础的部分。 递归遍历矩阵 1个目标文件,简单! 多人聊天室 3... -
JAVA上百实例源码以及开源项目源代码
2018-12-11 17:07:42Tcp服务端与客户端的JAVA实例源代码 2个目标文件 摘要:Java源码,文件操作,TCP,服务器 Tcp服务端与客户端的JAVA实例源代码,一个简单的Java TCP服务器端程序,别外还有一个客户端的程序,两者互相配合可以开发出超多... -
java自学之道
2014-01-05 20:17:041.1 面向对象程序设计入门分析 1.2 抽象 1.3 封装 2、类 2.1 类头 2.2类体 2.3 创建对象 2.4 面向对象举例 2.5 构造函数 2.5.1 构造函数的一般概念 2.5.2 创建自己的构造函数 2.5.3 构造方法注意事项 2.5.4构造... -
java课程实验
2012-12-02 16:51:192. 程序设计(开发环境不限): 1) 打印出100以内的素数 2) 求1!+2!+……+20! 3) 课后习题2.6 4) 编写程序,命令行窗口输出希腊字母表。(希腊字母表开始为α,最后一个为ω) 实验二 1、设计一个名为figure的... -
韩顺平Java从入门到精通视频笔记.doc
2018-05-05 11:43:07排序的介绍 38 冒泡法程序演示 38 选择式排序法--选择排序法 38 插入式排序法--插入排序法 39 交换式排序法--快速排序法 39 其它排序法--选堆排序法 40 其它排序法--希尔排序法 40 其它排序法--二叉树排序法 40 其它... -
《Java从入门到精通(第2版)》试读样章
2015-04-07 09:22:37第3篇【高级应用】主要讲解多线程、文件I/O操作、Java Applet网页小程序、Java网络程序设计、Java数据库编程以及DAO设计模式等;第4篇【项目实战】通过OA办公系统和电子商务网站平台两个实战案例,介绍了完整的Java... -
华农Java综合性实验手写界面代码
2014-12-09 09:29:58例如“2012级计算机科学与技术8班-面向对象程序设计.txt”文件中存放该班学生面向对象程序设计的考试成绩。内容为: 201230740801,赵一,68 201230740802,钱二,82 201230740803,孙三,58 201230740804,李四,62 ... -
java 面试题 总结
2009-09-16 08:45:34GC是垃圾收集的意思(Gabage Collection),内存处理是编程人员容易出现问题的地方,忘记或者错误的内存回收会导致程序或系统的不稳定甚至崩溃,Java提供的GC功能可以自动监测对象是否超过作用域从而达到自动回收... -
华农Java综合性实验拖拉控件界面代码
2014-12-09 10:35:11例如“2012级计算机科学与技术8班-面向对象程序设计.txt”文件中存放该班学生面向对象程序设计的考试成绩。内容为: 201230740801,赵一,68 201230740802,钱二,82 201230740803,孙三,58 201230740804,李四,62 ... -
java2实验实用模板代码
2010-11-25 10:30:38实验2 一个简单的JAVA APPLET程序 3 实验3 联合编译 4 上机实践2 基本数据类型与控制语句 6 实验1 输出希腊字母表 6 实验2 回文数 6 实验3 猜数字游戏 9 上机实践3 类与对象 10 实验1 三角形、梯形和圆形的类封装 10... -
Java JDK实例宝典
2016-06-16 19:27:14第1章 Java基础 1.1 转换基本数据类型 1.2 Java的运算符 1.3 控制程序的流程 1.4 计算阶乘 1.5 实现命令行程序 第2章 Java面向对象程序设计 2. 1 复数类 2. 2 equals.chashCode... -
Java经典编程300例(code)
2013-01-09 10:26:53实例056 Java对象的深克隆 82 实例057 序列化与对象克隆 84 实例058 深克隆效率的比较 87 第7章 面向对象进阶 89 实例059 经理与员工的差异 90 实例060 重写父类中的方法 92 实例061 计算几何图形的面积 93 实例062 ... -
JAVA面试题最全集
2010-03-13 13:09:10请写一个java程序实现线程连接池功能? 44.给定一个C语言函数,要求实现在java类中进行调用。 45.如何获得数组的长度? 46.访问修饰符“public/private/protected/缺省的修饰符”的使用 47.用关键字final修饰一... -
Java实现员工业绩管理系统?
2020-03-30 18:30:28# 具体要求 1、创建类实现基本实体对象和他们关系的管理,包括员工类、部门类、业绩类等。...## 写明设计思想、程序的结构、功能关系图、类的说明和类之间的关系图、程序主要执行流程图 怕被吞悬赏较低,采纳会追加 -
java入门经典第六版(扫描版)
2015-04-01 17:02:342.8 运行Java程序 2.9 总结 2.10 问与答 2.11 测验 2.11.1 问题 2.11.2 答案 2.12 练习 第3章 Java之旅 3.1 第一站:Oracle 3.2 去Java学校 3.3 在JavaWorld用午餐 3.4 在NASA... -
Java常用算法手册.赵志云(带详细书签).pdf
2018-10-23 00:12:53可以毫不夸张地说,算法是一切程序设计的灵魂和基础。选择合理的算法,可以起到事半功倍的效果。 赵志云、衡友跃编著的《Java常用算法手册》分三篇,共13章,分别介绍了算法基础、算法应用和算法面试题。首先介绍... -
《Java开发实战1200例(第I卷)》(李钟尉.陈丹丹).part1 高清完整PDF版
2016-06-13 15:46:48实例331 实现自动排序的列表 实例332 列表项的增加与删除 实例333 查找特定的列表元素 实例334 包含边框的列表元素 实例335 包含图片的列表元素 实例336 可以预览字体的列表 14.3 表格的简单应用 实例337 ... -
《Java开发实战1200例(第I卷)》(李钟尉.陈丹丹).part4 高清完整PDF版
2016-06-13 16:13:13实例331 实现自动排序的列表 实例332 列表项的增加与删除 实例333 查找特定的列表元素 实例334 包含边框的列表元素 实例335 包含图片的列表元素 实例336 可以预览字体的列表 14.3 表格的简单应用 实例337 ... -
《Java开发实战1200例(第I卷)》(李钟尉.陈丹丹).part2 高清完整PDF版
2016-06-13 15:53:27实例331 实现自动排序的列表 实例332 列表项的增加与删除 实例333 查找特定的列表元素 实例334 包含边框的列表元素 实例335 包含图片的列表元素 实例336 可以预览字体的列表 14.3 表格的简单应用 实例337 ... -
《Java开发实战1200例(第I卷)》(李钟尉.陈丹丹).part3 高清完整PDF版
2016-06-13 16:11:24实例331 实现自动排序的列表 实例332 列表项的增加与删除 实例333 查找特定的列表元素 实例334 包含边框的列表元素 实例335 包含图片的列表元素 实例336 可以预览字体的列表 14.3 表格的简单应用 实例337 ... -
《Java开发实战1200例(第I卷)》(李钟尉.陈丹丹).part5 高清完整PDF版
2016-06-13 16:17:38实例331 实现自动排序的列表 实例332 列表项的增加与删除 实例333 查找特定的列表元素 实例334 包含边框的列表元素 实例335 包含图片的列表元素 实例336 可以预览字体的列表 14.3 表格的简单应用 实例337 ...
收藏数
90
精华内容
36