├── .github └── workflows │ └── ant.yml ├── LICENSE ├── README.md └── src ├── Chapter01 ├── Exercise0101_Display_three_messages.java ├── Exercise0102_Display_five_messages.java ├── Exercise0103_Display_a_pattern.java ├── Exercise0104_Print_a_table.java ├── Exercise0105_Compute_expressions.java ├── Exercise0106_Summation_of_a_series.java ├── Exercise0107_Approximate_pi.java ├── Exercise0108_Area_and_perimeter_of_a_circle.java ├── Exercise0109_Area_and_perimeter_of_a_rectangle.java ├── Exercise0110_Average_speed_in_miles.java ├── Exercise0111_Population_projection.java └── Exercise0112_Average_speed_in_kilometers.java ├── Chapter02 ├── Exercise0201_Convert_mile_to_kilometer.java ├── Exercise0202_Compute_the_volume_of_a_triangle.java ├── Exercise0203_Convert_feet_into_meters.java ├── Exercise0204_Convert_pounds_into_kilograms.java ├── Exercise0205_Financial_application_calculate_tips.java ├── Exercise0206_Sum_the_digits_in_an_integer.java ├── Exercise0207_Find_the_number_of_years.java ├── Exercise0208_Current_time.java ├── Exercise0209_Physics_acceleration.java ├── Exercise0210_Science_calculating_energy.java ├── Exercise0211_Population_projection.java ├── Exercise0212_Physics_finding_runway_length.java ├── Exercise0213_Financial_application_compound_value.java ├── Exercise0214_Health_application_computing_BMI.java ├── Exercise0215_Geometry_distance_of_two_points.java ├── Exercise0216_Geometry_area_of_a_hexagon.java ├── Exercise0217_Science_wind_chill_temperature.java ├── Exercise0218_Print_a_table.java ├── Exercise0219_Geometry_area_of_a_triangle.java ├── Exercise0220_Financial_application_calculate_interest.java ├── Exercise0221_Financial_application_calculate_future_investment_value.java ├── Exercise0222_Financial_application_monetary_units.java └── Exercise0223_Cost_of_driving.java ├── Chapter03 ├── Exercise0301_Algebra_solve_quadratic_equations.java ├── Exercise0302_Game_multiply_three_numbers.java ├── Exercise0303_Algebra_solve_2x2_linear_equations.java ├── Exercise0304_Random_month.java ├── Exercise0305_Find_future_dates.java ├── Exercise0306_Health_application_BMI.java ├── Exercise0307_Financial_application_monetary_units.java ├── Exercise0308_Sort_three_integers.java ├── Exercise0309_Business_check_ISBN_10.java ├── Exercise0310_Game_addition_quiz.java ├── Exercise0311_Find_the_number_of_days_in_a_month.java ├── Exercise0312_Palindrome_number.java ├── Exercise0313_Financial_application_compute_taxes.java ├── Exercise0314_Game_heads_or_tails.java ├── Exercise0315_Game_lottery.java ├── Exercise0316_Random_point.java ├── Exercise0317_Game_scissor_rock_paper.java ├── Exercise0318_Cost_of_shipping.java ├── Exercise0319_Compute_the_perimeter_of_a_triangle.java ├── Exercise0320_Science_wind_chill_temperature.java ├── Exercise0321_Science_day_of_the_week.java ├── Exercise0322_Geometry_point_in_a_circle.java ├── Exercise0323_Geometry_point_in_a_rectangle.java ├── Exercise0324_Game_pick_a_card.java ├── Exercise0325_Geometry_intersecting_point.java ├── Exercise0326_Use_the_operators.java ├── Exercise0327_Geometry_points_in_triangle.java ├── Exercise0328_Geometry_two_rectangles.java ├── Exercise0329_Geometry_two_circles.java ├── Exercise0330_Current_time.java ├── Exercise0331_Financial_currency_exchange.java ├── Exercise0332_Geometry_point_position.java ├── Exercise0333_Financial_compare_costs.java ├── Exercise0334_Geometry_point_on_line_segment.java └── Exercise0335_Even_or_odd_number.java ├── Chapter04 ├── Exercise0401_Geometry_area_of_a_pentagon.java ├── Exercise0402_Geometry_great_circle_distance.java ├── Exercise0403_Geography_estimate_areas.java ├── Exercise0404_Geometry_area_of_a_hexagon.java ├── Exercise0405_Geometry_area_of_a_regular_polygon.java ├── Exercise0406_Random_points_on_a_circle.java ├── Exercise0407_Corner_point_coordinates.java ├── Exercise0408_Find_the_character_of_an_ASCII_code.java ├── Exercise0409_Find_the_Unicode_of_a_character.java ├── Exercise0410_Guess_birthday.java ├── Exercise0411_Binary_to_decimal.java ├── Exercise0412_Hex_to_binary.java ├── Exercise0413_Vowel_or_consonant.java ├── Exercise0414_Convert_letter_grade_to_number.java ├── Exercise0415_Phone_key_pads.java ├── Exercise0416_Random_character.java ├── Exercise0417_Days_of_a_month.java ├── Exercise0418_Student_major_and_status.java ├── Exercise0419_Business_check_ISBN_10.java ├── Exercise0420_Process_a_string.java ├── Exercise0421_Check_SSN.java ├── Exercise0422_Check_substring.java ├── Exercise0423_Financial_application_payroll.java ├── Exercise0424_Enter_three_countries.java ├── Exercise0425_Generate_vehicle_plate_numbers.java └── Exercise0426_Financial_application_monetary_units.java ├── Chapter05 ├── Exercise0501_Pass_or_fail.java ├── Exercise0502_Repeat_multiplications.java ├── Exercise0503_Conversion_from_Celsius_to_Fahrenheit.java ├── Exercise0504_Conversion_from_inch_to_centimeter.java ├── Exercise0505_Conversion_from_C_to_F_and_F_to_C.java ├── Exercise0506_Conversion_from_square_meter_to_ping.java ├── Exercise0507_Financial_application_compute_future_tuition.java ├── Exercise0508_Find_the_highest_score.java ├── Exercise0509_Find_the_two_lowest_scores.java ├── Exercise0510_Find_numbers_divisible_by_3_and_4.java ├── Exercise0511_Find_numbers_divisible_by_3_or_4_but_not_both.java ├── Exercise0512_Find_the_smallest_n_such_that_n3_bigger_than_12000.java ├── Exercise0513_Find_the_largest_n_such_that_n2_smaller_than_12000.java ├── Exercise0514_Compute_the_greatest_common_divisor.java ├── Exercise0515_Display_the_ASCII_character_table.java ├── Exercise0516_Find_the_factors_of_an_integer.java ├── Exercise0517_Display_pyramid.java ├── Exercise0518_Display_four_patterns_using_loops.java ├── Exercise0519_Display_numbers_in_a_pyramid_pattern.java ├── Exercise0520_Display_prime_number_between_2_and_1200.java ├── Exercise0521_Financial_application_compare_loans_with_various_interest_rates.java ├── Exercise0522_Financial_application_loan_amortization_schedule.java ├── Exercise0523_Demonstrate_cancellation_errors.java ├── Exercise0524_Sum_a_series.java ├── Exercise0525_Compute_PI.java ├── Exercise0526_Compute_e.java ├── Exercise0527_Display_leap_years.java ├── Exercise0528_Display_the_first_days_of_each_month.java ├── Exercise0529_Display_Calendars.java ├── Exercise0530_Financial_application_compound_value.java ├── Exercise0531_Financial_application_compute_CD_value.java ├── Exercise0532_Game_lottery.java ├── Exercise0533_Perfect_number.java ├── Exercise0534_Game_scissor_rock_paper.java ├── Exercise0535_Summation.java ├── Exercise0536_Business_application_checking_ISBN.java ├── Exercise0537_Decimal_to_binary.java ├── Exercise0538_Decimal_to_octal.java ├── Exercise0539_Financial_application_find_the_sales_amount.java ├── Exercise0540_Simulation_heads_or_tails.java ├── Exercise0541_Occurrence_of_max_numbers.java ├── Exercise0542_Financial_application_find_the_sales_amount.java ├── Exercise0543_Math_combinations.java ├── Exercise0544_Computer_architecture_bit_level_operations.java ├── Exercise0545_Statistics_compute_mean_and_standard_deviation.java ├── Exercise0546_Reverse_a_string.java ├── Exercise0547_Business_check_ISBN_13.java ├── Exercise0548_Process_string.java ├── Exercise0549_Count_vowels_and_consonants.java ├── Exercise0550_Print_multiplication_table.java └── Exercise0551_Longest_common_prefix.java ├── Chapter06 ├── Exercise0601_Math_pentagonal_numbers.java ├── Exercise0602_Sum_the_digits_in_an_integer.java ├── Exercise0603_Palindrome_integer.java ├── Exercise0604_Display_an_integer_reversed.java ├── Exercise0605_Sort_three_numbers.java ├── Exercise0606_Display_patterns.java ├── Exercise0607_Financial_application_compute_the_future_investment_value.java ├── Exercise0608_Conversions_between_mile_and_kilometer.java ├── Exercise0609_Conversions_between_pounds_and_kilograms.java ├── Exercise0610_Use_the_isPrime_Method.java ├── Exercise0611_Financial_application_compute_commissions.java ├── Exercise0612_Display_numbers.java ├── Exercise0613_Sum_series.java ├── Exercise0614_Estimate_PI.java ├── Exercise0615_Financial_application_print_a_tax_table.java ├── Exercise0616_Number_of_days_in_a_year.java ├── Exercise0617_Display_matrix_of_0s_and_1s.java ├── Exercise0618_Check_password.java ├── Exercise0619_Triangles.java ├── Exercise0620_Count_the_letters_in_a_string.java ├── Exercise0621_Phone_keypads.java ├── Exercise0622_Math_approximate_the_square_root.java ├── Exercise0623_Occurrences_of_a_specified_character.java ├── Exercise0624_Display_current_date_and_time.java ├── Exercise0625_Convert_milliseconds_to_hours_minutes_and_seconds.java ├── Exercise0626_Palindromic_prime.java ├── Exercise0627_Emirp.java ├── Exercise0628_Mersenne_prime.java ├── Exercise0629_Twin_primes.java ├── Exercise0630_Game_craps.java ├── Exercise0631_Financial_credit_card_number_validation.java ├── Exercise0632_Game_chance_of_winning_at_craps.java ├── Exercise0633_Current_date_and_time.java ├── Exercise0634_Print_calendar.java ├── Exercise0635_Geometry_area_of_a_pentagon.java ├── Exercise0636_Geometry_area_of_a_regular_polygon.java ├── Exercise0637_Format_an_integer.java ├── Exercise0638_Generate_random_characters.java └── Exercise0639_Geometry_point_position.java └── Chapter07 ├── Exercise0701_Assign_grades.java ├── Exercise0702_Comparing_numbers.java ├── Exercise0703_Count_occurrence_of_numbers.java ├── Exercise0704_Analyze_scores.java ├── Exercise0705_The_number_of_even_numbers_and_odd_numbers.java ├── Exercise0706_The_Sieve_of_Eratosthenes.java ├── Exercise0707_Count_single_digits.java ├── Exercise0708_Average_an_array.java ├── Exercise0709_Find_the_largest_element.java ├── Exercise0710_Find_the_index_of_the_largest_element.java ├── Exercise0711_Statistics_compute_deviation.java ├── Exercise0712_Reverse_an_array.java ├── Exercise0713_Random_number_selector.java ├── Exercise0714_Computing_lcm.java ├── Exercise0715_Eliminate_duplicates.java ├── Exercise0716_Execution_time.java ├── Exercise0717_Sort_students.java ├── Exercise0718_Bubble_sort.java ├── Exercise0719_Sorted.java ├── Exercise0720_Descending_Bubble_Sort.java ├── Exercise0721_Normalizing_integers.java ├── Exercise0722_Count_the_number_of_vowels_in_a_string.java ├── Exercise0723_Game_locker_puzzle.java ├── Exercise0724_Simulation_coupon_collectors_problem.java ├── Exercise0725_Algebra_solve_quadratic_equations.java ├── Exercise0726_Check_whether_array_is_sorted.java ├── Exercise0727_Check_whether_the_array_is_sorted_with_constant_interval.java ├── Exercise0728_Math_permutations.java ├── Exercise0729_Game_dice.java ├── Exercise0730_Pattern_recognition_consecutive_four_equal_numbers.java ├── Exercise0731_Merge_two_sorted_lists.java ├── Exercise0732_Partition_of_a_list.java ├── Exercise0733_Month_name.java ├── Exercise0734_Sort_characters_in_a_string.java ├── Exercise0735_Game_hangman.java ├── Exercise0736_Game_Eight_Queens.java └── Exercise0737_Game_bean_machine.java /.github/workflows/ant.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Set up JDK 1.8 13 | uses: actions/setup-java@v1 14 | with: 15 | java-version: 1.8 16 | - name: Build with Ant 17 | run: ant -noinput -buildfile build.xml 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Sven 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0101_Display_three_messages.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display three messages) Write a program that displays Welcome to Java, 3 | * Learning Java Now, and Programming is fun. 4 | * 5 | * Created by Sven on 8/16/2018. 6 | */ 7 | package Chapter01; 8 | 9 | public class Exercise0101_Display_three_messages { 10 | public static void main(String[] args) { 11 | System.out.println("Welcome to Java"); 12 | System.out.println("Learning Java Now"); 13 | System.out.println("Programming is fun"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0102_Display_five_messages.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display five messages) Write a program that displays I love Java five times. 3 | * 4 | * Created by Sven on 8/16/2018. 5 | */ 6 | package Chapter01; 7 | 8 | public class Exercise0102_Display_five_messages { 9 | public static void main(String[] args) { 10 | System.out.println("I love Java"); 11 | System.out.println("I love Java"); 12 | System.out.println("I love Java"); 13 | System.out.println("I love Java"); 14 | System.out.println("I love Java"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0103_Display_a_pattern.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display a pattern) Write a program that displays the following pattern: 3 | * J A V V A 4 | * J A A V V A A 5 | * J J AAAAA V V AAAAA 6 | * J J A A V A A 7 | * 8 | * Created by Sven on 8/16/2018. 9 | */ 10 | package Chapter01; 11 | 12 | public class Exercise0103_Display_a_pattern { 13 | public static void main(String[] args) { 14 | System.out.println(" J A V V A"); 15 | System.out.println(" J A A V V A A"); 16 | System.out.println("J J AAAAA V V AAAAA"); 17 | System.out.println(" J J A A V A A"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0104_Print_a_table.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Print a table) Write a program that displays the following table: 3 | * a a^2 a^3 a^4 4 | * 1 1 1 1 5 | * 2 4 8 16 6 | * 3 9 27 81 7 | * 4 16 64 256 8 | * 9 | * Created by Sven on 8/16/2018. 10 | */ 11 | package Chapter01; 12 | 13 | public class Exercise0104_Print_a_table { 14 | public static void main(String[] args) { 15 | System.out.println("a a^2 a^3 a^4"); 16 | System.out.println("1 1 1 1"); 17 | System.out.println("2 4 8 16"); 18 | System.out.println("3 9 27 81"); 19 | System.out.println("4 16 64 256"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0105_Compute_expressions.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Compute expressions) Write a program that displays the result of 3 | * (7.5 * 6.5 - 4.5 * 3) / (47.5 - 5.5). 4 | * 5 | * Created by Sven on 8/16/2018. 6 | */ 7 | package Chapter01; 8 | 9 | public class Exercise0105_Compute_expressions { 10 | public static void main(String[] args) { 11 | System.out.println((7.5 * 6.5 - 4.5 * 3) / (47.5 - 5.5)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0106_Summation_of_a_series.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Summation of a series) Write a program that displays the result of 3 | * 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10. 4 | * 5 | * Created by Sven on 8/16/2018. 6 | */ 7 | package Chapter01; 8 | 9 | public class Exercise0106_Summation_of_a_series { 10 | public static void main(String[] args) { 11 | System.out.println(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0107_Approximate_pi.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Approximate pi) pi can be computed using the following formula: 3 | * PI = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...) 4 | * Write a program that displays the result of 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11) 5 | * and 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13). Use 1.0 instead of 1 in your 6 | * program. 7 | * 8 | * Created by Sven on 8/16/2018. 9 | */ 10 | package Chapter01; 11 | 12 | public class Exercise0107_Approximate_pi { 13 | public static void main(String[] args) { 14 | System.out.println(4 * (1.0 - 1.0 / 3 + 1.0 / 5 - 1.0 / 7 + 1.0 / 9 - 1.0 / 11)); 15 | System.out.println(4 * (1.0 - 1.0 / 3 + 1.0 / 5 - 1.0 / 7 + 1.0 / 9 - 1.0 / 11 + 1.0 / 13)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0108_Area_and_perimeter_of_a_circle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Area and perimeter of a circle) Write a program that displays the area and perimeter 3 | * of a circle that has a radius of 6.5 using the following formula: 4 | * PI = 3.14159 5 | * perimeter = 2 * radius * pi 6 | * area = radius * radius * pi 7 | * 8 | * Created by Sven on 8/16/2018. 9 | */ 10 | package Chapter01; 11 | 12 | public class Exercise0108_Area_and_perimeter_of_a_circle { 13 | public static void main(String[] args) { 14 | System.out.println("The area of a circle that has a radius of 6.5 is " + 6.5 * 6.5 * 3.14159); 15 | System.out.println("The perimeter of a circle that has a radius of 6.5 is " + 2 * 6.5 * 3.14159); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0109_Area_and_perimeter_of_a_rectangle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Area and perimeter of a rectangle) Write a program that displays the area and perimeter 3 | * of a rectangle with a width of 5.3 and height of 8.6 using the following formula: 4 | * area = width * height 5 | * perimeter = 2 * (width + height) 6 | * 7 | * Created by Sven on 8/16/2018. 8 | */ 9 | package Chapter01; 10 | 11 | public class Exercise0109_Area_and_perimeter_of_a_rectangle { 12 | public static void main(String[] args) { 13 | System.out.println("The area of a rectangle with the width of 5.3 and height of 8.6 is " + 5.3 * 8.6); 14 | System.out.println("The perimeter of a rectangle with the width of 5.3 and height of 8.6 is " + 2 * (5.3 + 8.6)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0110_Average_speed_in_miles.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Average speed in miles) Assume that a runner runs 15 kilometers in 50 minutes 3 | * and 30 seconds. Write a program that displays the average speed in miles per hour. 4 | * (Note that 1 mile is 1.6 kilometers.) 5 | * 6 | * Created by Sven on 8/16/2018. 7 | */ 8 | package Chapter01; 9 | 10 | public class Exercise0110_Average_speed_in_miles { 11 | public static void main(String[] args) { 12 | System.out.println("The average speed is " + (15 / 1.6) / (50.0 / 60 + 30.0 / 60 / 60) + " mph"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Chapter01/Exercise0112_Average_speed_in_kilometers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Average speed in kilometers) Assume that a runner runs 24 miles in 1 hour, 40 3 | * minutes, and 35 seconds. Write a program that displays the average speed in 4 | * kilometers per hour. (Note 1 mile is equal to 1.6 kilometers.) 5 | * 6 | * Created by Sven on 8/16/2018. 7 | */ 8 | package Chapter01; 9 | 10 | public class Exercise0112_Average_speed_in_kilometers { 11 | public static void main(String[] args) { 12 | System.out.println("The average speed is " + (24 * 1.6 / (1 + 40.0 / 60 + 35.0 / 60 / 60)) + " km/h"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0201_Convert_mile_to_kilometer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * ((Convert mile to kilometer) Write a program that reads a mile in a double value 3 | * from the console, converts it to kilometers, and displays the result. The formula 4 | * for the conversion is as follows: 5 | * 1 mile = 1.6 kilometers 6 | * 7 | * Here is a sample run: 8 | * Enter miles: 96 9 | * 96 miles is 153.6 kilometers 10 | * 11 | * Created by Sven on 8/17/2018. 12 | */ 13 | package Chapter02; 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise0201_Convert_mile_to_kilometer { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | System.out.print("Enter miles: "); 21 | double miles = input.nextDouble(); 22 | double kilometers = miles * 1.6; 23 | System.out.println(miles + " miles is " + kilometers + " kilometers"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0202_Compute_the_volume_of_a_triangle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Compute the volume of a triangle) Write a program that reads in the length of 3 | * sides of an equilateral triangle and computes the area and volume using the following 4 | * formulas: 5 | * area = sqrt(3) / 4 *(length of sides)^2 6 | * volume = area * length 7 | * 8 | * Here is a sample run: 9 | * Enter length of the sides and height of the Equilateral 10 | * triangle: 3.5 11 | * The area is 3.89 [Should be 5.30?] 12 | * The volume of the Triangular prism is 19.48 [Should be 18.56?] 13 | * 14 | * Created by Sven on 8/17/2018. 15 | */ 16 | package Chapter02; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0202_Compute_the_volume_of_a_triangle { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter length of the sides and height of the Equilateral triangle: "); 24 | double sideLength = input.nextDouble(); 25 | 26 | double area = Math.pow(3, 0.5) / 4 * Math.pow(sideLength, 2); 27 | double volume = area * sideLength; 28 | System.out.println("The area is " + area); 29 | System.out.println("The volume of the Triangular prism is " + volume); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0203_Convert_feet_into_meters.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Convert meters into feet) Write a program that reads a number in meters, converts 3 | * it to feet, and displays the result. One meter is 3.2786 feet. 4 | * 5 | * Here is a sample run: 6 | * Enter a value for meter: 10 7 | * 10.0 meters is 32.786 feet 8 | * 9 | * Created by Sven on 8/17/2018. 10 | */ 11 | package Chapter02; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0203_Convert_feet_into_meters { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter a value for meter: "); 19 | double meters = input.nextDouble(); 20 | 21 | double feet = meters * 3.2786; 22 | System.out.println(meters + " meters is " + feet + " feet"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0204_Convert_pounds_into_kilograms.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Convert square meter into ping) Write a program that converts square meter into ping. 3 | * The program prompts the user to enter a number in square meter, converts it to ping, 4 | * and displays the result. One square meter is 0.3025 ping. 5 | * 6 | * Here is a sample run: 7 | * Enter a number in square meters: 50 8 | * 50.0 square meters is 15.125 pings 9 | * 10 | * Created by Sven on 8/17/2018. 11 | */ 12 | package Chapter02; 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise0204_Convert_pounds_into_kilograms { 17 | public static void main(String[] args) { 18 | Scanner input = new Scanner(System.in); 19 | System.out.println("Enter a number in square meters: "); 20 | double squareMeters = input.nextDouble(); 21 | 22 | double pings = squareMeters * 0.3025; 23 | System.out.println(squareMeters + " square meters is " + pings + " pings"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0205_Financial_application_calculate_tips.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: calculate tips) Write a program that reads the subtotal 3 | * and the gratuity rate and then computes the gratuity and total. For example, if the 4 | * user enters 10 for subtotal and 12% for gratuity rate, the program displays $1.2 5 | * as gratuity and $11.2 as total. 6 | * 7 | * Here is a sample run: 8 | * Enter the subtotal and a gratuity rate: 10 12 9 | * The gratuity is $1.2 and total is $11.2 10 | * 11 | * Created by Sven on 8/17/2018. 12 | */ 13 | package Chapter02; 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise0205_Financial_application_calculate_tips { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | System.out.print("Enter the subtotal and a gratuity rate: "); 21 | double subtotal = input.nextDouble(); 22 | double gratuityRate = input.nextDouble() / 100.0; 23 | 24 | double gratuity = subtotal * gratuityRate; 25 | double total = subtotal + gratuity; 26 | System.out.println("The gratuity is $" + gratuity + " and total is $" + total); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0206_Sum_the_digits_in_an_integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Multiply the digits in an integer) Write a program that reads an integer between 3 | * 0 and 1000 and multiplies all the digits in the integer. For example, if an integer 4 | * is 932, the multiplication of all its digits is 54. 5 | * Hint: Use the % operator to extract digits, and use the / operator to remove the 6 | * extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93. 7 | * 8 | * Here is a sample run: 9 | * Enter a number between 0 and 1000: 999 10 | * The multiplication of all digits in 999 is 729 11 | * 12 | * Created by Sven on 8/17/2018. 13 | */ 14 | package Chapter02; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0206_Sum_the_digits_in_an_integer { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | 22 | System.out.print("Enter an integer number between 0 and 1000: "); 23 | int initialNumber = input.nextInt(); 24 | 25 | int number = initialNumber; 26 | int multiplication = initialNumber % 10; 27 | 28 | if (initialNumber > 1000 || initialNumber < 0) { 29 | System.out.println("Out of range!"); 30 | System.out.println("Number should be between 0 & 1000!"); 31 | } else { 32 | while (number / 10 != 0) { 33 | number = number / 10; 34 | multiplication *= number % 10; 35 | } 36 | 37 | System.out.println("Multiplication of the digits in the number " 38 | + initialNumber + " equals to " + multiplication); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0207_Find_the_number_of_years.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the number of years) Write a program that prompts the user to enter the 3 | * minutes (e.g., 1 billion), and displays the number of years and remaining days for 4 | * the minutes. For simplicity, assume that a year has 365 days. 5 | * 6 | * Here is a sample run: 7 | * Enter the number of minutes: 1000000000 8 | * 1000000000 minutes is approximately 1902 years and 214 days 9 | * 10 | * Created by Sven on 8/17/2018. 11 | */ 12 | package Chapter02; 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise0207_Find_the_number_of_years { 17 | public static void main(String[] args) { 18 | Scanner input = new Scanner(System.in); 19 | System.out.print("Enter the number of minutes: "); 20 | int minutes = input.nextInt(); 21 | 22 | int totalDays = minutes / 60 / 24; 23 | int totalYears = totalDays / 365; 24 | int remainDays = totalDays - totalYears * 365; 25 | System.out.println(minutes + " minutes is approximately " + totalYears + " years and " + remainDays + " days"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0208_Current_time.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays 3 | * the current time in GMT. Revise the program so it prompts the user to enter the 4 | * time zone offset to GMT and displays the time in the specified time zone. 5 | * 6 | * Here is a sample run: 7 | * Enter the time zone offset to GMT: −5 8 | * The current time is 4:50:34 9 | * 10 | * Created by Sven on 8/17/2018. 11 | */ 12 | package Chapter02; 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise0208_Current_time { 17 | public static void main(String[] args) { 18 | Scanner input = new Scanner(System.in); 19 | System.out.print("Enter the time zone offset to GMT: "); 20 | int timeZone = input.nextInt(); 21 | 22 | long totalMilliseconds = System.currentTimeMillis(); 23 | long totalSeconds = totalMilliseconds / 1000; 24 | long currentSecond = totalSeconds % 60; 25 | long totalMinutes = totalSeconds / 60; 26 | long currentMinute = totalMinutes % 60; 27 | long totalHours = totalMinutes / 60; 28 | long currentHour = (totalHours + timeZone) % 24; 29 | 30 | System.out.println("The current time is " + currentHour + ":" + currentMinute + ":" + currentSecond); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0209_Physics_acceleration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Physics: acceleration) Average acceleration is defined as the change of velocity 3 | * divided by the time taken to make the change, as given by the following formula: 4 | * a = (v1 - v0) / t 5 | * Write a program that prompts the user to enter the starting velocity v0 in meters/ 6 | * second, the ending velocity v1 in meters/second, and the time span t in seconds, 7 | * then displays the average acceleration. 8 | * 9 | * Here is a sample run: 10 | * Enter v0, v1, and t: 5.5 50.9 4.5 11 | * The average acceleration is 10.0889 12 | * 13 | * Created by Sven on 8/17/2018. 14 | */ 15 | package Chapter02; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0209_Physics_acceleration { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter v0, v1, and t: "); 23 | double v0 = input.nextDouble(); 24 | double v1 = input.nextDouble(); 25 | double t = input.nextDouble(); 26 | 27 | System.out.println("The average acceleration is " + (v1 - v0) / t); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0210_Science_calculating_energy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Science: calculating energy) Write a program that calculates the energy needed 3 | * to heat water from an initial temperature to a final temperature. Your program 4 | * should prompt the user to enter the amount of water in kilograms and the initial 5 | * and final temperatures of the water. The formula to compute the energy is 6 | * Q = M * (finalTemperature – initialTemperature) * 4184 7 | * where M is the weight of water in kilograms, initial and final temperatures are in 8 | * degrees Celsius, and energy Q is measured in joules. Here is a sample run: 9 | * 10 | * Here is a sample run: 11 | * Enter the amount of water in kilograms: 55.5 12 | * Enter the initial temperature: 3.5 13 | * Enter the final temperature: 10.5 14 | * The energy needed is 1625484.0 15 | * 16 | * Created by Sven on 8/17/2018. 17 | */ 18 | package Chapter02; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0210_Science_calculating_energy { 23 | public static void main(String[] args) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter the amount of water in kilograms: "); 26 | double amount = input.nextDouble(); 27 | System.out.print("Enter the initial temperature: "); 28 | double initialTemperature = input.nextDouble(); 29 | System.out.print("Enter the final temperature: "); 30 | double finalTemperature = input.nextDouble(); 31 | 32 | System.out.println("The energy needed is " + amount * (finalTemperature - initialTemperature) * 4184); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0211_Population_projection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Population projection) Rewrite Programming Exercise 1.11 to prompt the user 3 | * to enter the number of years and display the population after the number of years. 4 | * Use the hint in Programming Exercise 1.11 for this program. 5 | * 6 | * Here is a sample run of the program: 7 | * Enter the number of years: 5 8 | * The population in 5 years is 325932970 9 | * 10 | * Created by Sven on 8/17/2018. 11 | */ 12 | package Chapter02; 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise0211_Population_projection { 17 | public static void main(String[] args) { 18 | Scanner input = new Scanner(System.in); 19 | System.out.print("Enter the number of years: "); 20 | int numberOfYears = input.nextInt(); 21 | 22 | int secondsInYear = 365 * 24 * 60 * 60; 23 | double birthNumberInYear = secondsInYear / 7.0; 24 | double deathNumberInYear = secondsInYear / 13.0; 25 | double immigrantNumberInYear = secondsInYear / 45.0; 26 | double population = 312032486; 27 | 28 | population = population + (birthNumberInYear - deathNumberInYear + immigrantNumberInYear) * numberOfYears; 29 | 30 | System.out.println("The population in " + numberOfYears + " years is " + (int) population); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0212_Physics_finding_runway_length.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Physics: finding runway length) Given an airplane’s acceleration a and take-off 3 | * speed v, you can compute the minimum runway length needed for an airplane to 4 | * take off using the following formula: 5 | * length = v^2 / 2a 6 | * Write a program that prompts the user to enter v in meters/second (m/s) and the 7 | * acceleration a in meters/second squared (m/s2), then, displays the minimum runway 8 | * length. 9 | * 10 | * Here is a sample run: 11 | * Enter speed and acceleration: 60 3.5 12 | * The minimum runway length for this airplane is 514.286 13 | * 14 | * Created by Sven on 8/17/2018. 15 | */ 16 | package Chapter02; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0212_Physics_finding_runway_length { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter speed and acceleration: "); 24 | double speed = input.nextDouble(); 25 | double acceleration = input.nextDouble(); 26 | 27 | double length = speed * speed / (2 * acceleration); 28 | System.out.println("The minimum runway length for this airplane is " + length); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0214_Health_application_computing_BMI.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Health application: computing BMI) Body Mass Index (BMI) is a measure of 3 | * health on weight. It can be calculated by taking your weight in kilograms and 4 | * dividing, by the square of your height in meters. Write a program that prompts the 5 | * user to enter a weight in pounds and height in inches and displays the BMI. Note 6 | * one pound is 0.45359237 kilograms and one inch is 0.0254 meters. 7 | * 8 | * Here is a sample run: 9 | * Enter weight in pounds: 95.5 10 | * Enter height in inches: 50 11 | * BMI is 26.8573 12 | * 13 | * Created by Sven on 8/17/2018. 14 | */ 15 | package Chapter02; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0214_Health_application_computing_BMI { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter weight in pounds: "); 23 | double weightInPounds = input.nextDouble(); 24 | System.out.print("Enter height in inches: "); 25 | double heightInInches = input.nextDouble(); 26 | 27 | double weightInKilograms = weightInPounds * 0.45359237; 28 | double heightInMeters = heightInInches * 0.0254; 29 | 30 | double BMI = weightInKilograms / (heightInMeters * heightInMeters); 31 | System.out.println("BMI is " + BMI); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0215_Geometry_distance_of_two_points.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: distance of two points) Write a program that prompts the user to enter 3 | * two points (x1, y1) and (x2, y2) and displays their distance. The formula for 4 | * computing the distance is sqrt((x2 - x1)^2 + (y2 - y1)^2).Note that you can use 5 | * Math.pow(a, 0.5) to compute sqrt(a). 6 | * 7 | * Here is a sample run: 8 | * Enter x1 and y1: 1.5 -3.4 9 | * Enter x2 and y2: 4 5 10 | * The distance between the two points is 8.764131445842194 11 | * 12 | * Created by Sven on 8/17/2018. 13 | */ 14 | package Chapter02; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0215_Geometry_distance_of_two_points { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter x1 and y1: "); 22 | double x1 = input.nextDouble(); 23 | double y1 = input.nextDouble(); 24 | System.out.print("Enter x2 and y2: "); 25 | double x2 = input.nextDouble(); 26 | double y2 = input.nextDouble(); 27 | 28 | double distance = Math.pow((Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)), 0.5); 29 | System.out.println("The distance between the two points is " + distance); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0216_Geometry_area_of_a_hexagon.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: area of a hexagon) Write a program that prompts the user to enter the 3 | * side of a hexagon and displays its area. The formula for computing the area of a 4 | * hexagon is 5 | * Area = (3 * sqrt(3)/ 2) * s^2 6 | * where s is the length of a side. 7 | * 8 | * Here is a sample run: 9 | * Enter the side: 5.5 10 | * The area of the hexagon is 78.5918 11 | * 12 | * Created by Sven on 8/17/2018. 13 | */ 14 | package Chapter02; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0216_Geometry_area_of_a_hexagon { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter the side: "); 22 | double side = input.nextDouble(); 23 | 24 | double area = (3 * Math.pow(3, 0.5) / 2) * Math.pow(side, 2); 25 | System.out.println("The area of the hexagon is " + area); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0217_Science_wind_chill_temperature.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Science: wind-chill temperature) How cold is it outside? The temperature alone 3 | * is not enough to provide the answer. Other factors including wind speed, relative 4 | * humidity, and sunshine play important roles in determining coldness outside. In 2001, 5 | * the National Weather Service (NWS) implemented the new wind-chill temperature 6 | * to measure the coldness using temperature and wind speed. The formula is 7 | * twc = 35.74 + 0.6215ta - 35.75v^0.16 + 0.4275tav^0.16 8 | * where ta is the outside temperature measured in degrees Fahrenheit, v is the speed 9 | * measured in miles per hour, and twc is the wind-chill temperature. The formula 10 | * cannot be used for wind speeds below 2 mph or temperatures below -58ºF or 11 | * above 41ºF. 12 | * Write a program that prompts the user to enter a temperature between -58ºF 13 | * and 41ºF and a wind speed greater than or equal to 2 then displays the wind-chill 14 | * temperature. Use Math.pow(a, b) to compute v^0.16. 15 | * 16 | * Here is a sample run: 17 | * Enter the temperature in Fahrenheit between -58ºF and 41ºF: 5.3 18 | * Enter the wind speed (>=2) in miles per hour: 6 19 | * The wind chill index is -5.56707 20 | * 21 | * Created by Sven on 8/17/2018. 22 | */ 23 | package Chapter02; 24 | 25 | import java.util.Scanner; 26 | 27 | public class Exercise0217_Science_wind_chill_temperature { 28 | public static void main(String[] args) { 29 | Scanner input = new Scanner(System.in); 30 | System.out.print("Enter the temperature in Fahrenheit between -58ºF and 41ºF: "); 31 | double ta = input.nextDouble(); 32 | System.out.print("Enter the wind speed (>=2) in miles per hour: "); 33 | double v = input.nextDouble(); 34 | 35 | double twc = 35.74 + 0.6215 * ta - 35.75 * Math.pow(v, 0.16) + 0.4275 * ta * Math.pow(v, 0.16); 36 | System.out.println("The wind chill index is " + twc); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0218_Print_a_table.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Print a table) Write a program that displays the following table. Calculate the 3 | * middle point of two points. 4 | * a b Middle Point 5 | * (0, 0) (2, 1) (1.0, 0.5) 6 | * (1, 4) (4, 2) (2.5, 3.0) 7 | * (2, 7) (6, 3) (4.0, 5.0) 8 | * (3, 9) (10, 5) (6.5, 7.0) 9 | * (4, 11) (12, 7) (8.0, 9.0) 10 | * 11 | * Created by Sven on 8/17/2018. 12 | */ 13 | package Chapter02; 14 | 15 | public class Exercise0218_Print_a_table { 16 | public static void main(String[] args) { 17 | int x1, y1, x2, y2; 18 | System.out.println(" a b Middle Point"); 19 | x1 = 0; 20 | y1 = 0; 21 | x2 = 2; 22 | y2 = 1; 23 | System.out.println("(" + x1 + ", " + y1 + ") " + "(" + x2 + ", " + y2 + ") " + 24 | "(" + (x1 + x2) / 2.0 + ", " + (y1 + y2) / 2.0 + ")"); 25 | x1 = 1; 26 | y1 = 4; 27 | x2 = 4; 28 | y2 = 2; 29 | System.out.println("(" + x1 + ", " + y1 + ") " + "(" + x2 + ", " + y2 + ") " + 30 | "(" + (x1 + x2) / 2.0 + ", " + (y1 + y2) / 2.0 + ")"); 31 | x1 = 2; 32 | y1 = 7; 33 | x2 = 6; 34 | y2 = 3; 35 | System.out.println("(" + x1 + ", " + y1 + ") " + "(" + x2 + ", " + y2 + ") " + 36 | "(" + (x1 + x2) / 2.0 + ", " + (y1 + y2) / 2.0 + ")"); 37 | x1 = 3; 38 | y1 = 9; 39 | x2 = 10; 40 | y2 = 5; 41 | System.out.println("(" + x1 + ", " + y1 + ") " + "(" + x2 + ", " + y2 + ") " + 42 | "(" + (x1 + x2) / 2.0 + ", " + (y1 + y2) / 2.0 + ")"); 43 | x1 = 4; 44 | y1 = 11; 45 | x2 = 12; 46 | y2 = 7; 47 | System.out.println("(" + x1 + ", " + y1 + ") " + "(" + x2 + ", " + y2 + ") " + 48 | "(" + (x1 + x2) / 2.0 + ", " + (y1 + y2) / 2.0 + ")"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0219_Geometry_area_of_a_triangle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: area of a triangle) Write a program that prompts the user to enter three 3 | * points, (x1, y1), (x2, y2), and (x3, y3), of a triangle then displays its area. 4 | * The formula for computing the area of a triangle is 5 | * s = (side1 + side2 + side3)/2 6 | * area =sqrt(s(s - side1)(s - side2)(s - side3)) 7 | * 8 | * Here is a sample run: 9 | * Enter three points for a triangle: 1.5 -3.4 4.6 5 9.5 -3.4 10 | * The area of the triangle is 33.6 11 | * 12 | * Created by Sven on 8/17/2018. 13 | */ 14 | package Chapter02; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0219_Geometry_area_of_a_triangle { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter three points for a triangle: "); 22 | double x1 = input.nextDouble(); 23 | double y1 = input.nextDouble(); 24 | double x2 = input.nextDouble(); 25 | double y2 = input.nextDouble(); 26 | double x3 = input.nextDouble(); 27 | double y3 = input.nextDouble(); 28 | 29 | double side1 = Math.pow((Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2)), 0.5); 30 | double side2 = Math.pow((Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2)), 0.5); 31 | double side3 = Math.pow((Math.pow((x2 - x3), 2) + Math.pow((y2 - y3), 2)), 0.5); 32 | double s = (side1 + side2 + side3) / 2; 33 | 34 | double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5); 35 | System.out.println("The area of the triangle is " + area); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0220_Financial_application_calculate_interest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: calculate interest) If you know the balance and the annual 3 | * percentage interest rate, you can compute the interest on the next monthly payment 4 | * using the following formula: 5 | * interest = balance * (annualInterestRate / 1200) 6 | * Write a program that reads the balance and the annual percentage interest rate and 7 | * displays the interest for the next month. 8 | * 9 | * Here is a sample run: 10 | * Enter balance and interest rate (e.g., 3 for 3%): 1000 3.5 11 | * The interest is 2.91667 12 | * 13 | * Created by Sven on 8/17/2018. 14 | */ 15 | package Chapter02; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0220_Financial_application_calculate_interest { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter balance and interest rate (e.g., 3 for 3%): "); 23 | double balance = input.nextDouble(); 24 | double annualInterestRate = input.nextDouble(); 25 | 26 | double interest = balance * (annualInterestRate / 1200); 27 | System.out.println("The interest is " + interest); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0221_Financial_application_calculate_future_investment_value.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: calculate future investment value) Write a program that 3 | * reads in investment amount, annual interest rate, and number of years and displays 4 | * the future investment value using the following formula: 5 | * futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate)^(numberOfYears * 12) 6 | * For example, if you enter amount 1000, annual interest rate 3.25%, and number 7 | * of years 1, the future investment value is 1032.98. 8 | * 9 | * Here is a sample run: 10 | * Enter investment amount: 1000.56 11 | * Enter annual interest rate in percentage: 4.25 12 | * Enter number of years: 1 13 | * Accumulated value is $1043.92 14 | * 15 | * Created by Sven on 8/17/2018. 16 | */ 17 | package Chapter02; 18 | 19 | import java.util.Scanner; 20 | 21 | public class Exercise0221_Financial_application_calculate_future_investment_value { 22 | public static void main(String[] args) { 23 | Scanner input = new Scanner(System.in); 24 | System.out.print("Enter investment amount: "); 25 | double investmentAmount = input.nextDouble(); 26 | System.out.print("Enter annual interest rate in percentage: "); 27 | double annualInterestRate = input.nextDouble() / 100; 28 | double monthlyInterestRate = annualInterestRate / 12; 29 | System.out.print("Enter number of years: "); 30 | int numberOfYears = input.nextInt(); 31 | 32 | double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), numberOfYears * 12); 33 | System.out.println("Accumulated value is $" + futureInvestmentValue); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0222_Financial_application_monetary_units.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: monetary units) Rewrite Listing 2.10, ComputeChange. 3 | * java, to fix the possible loss of accuracy when converting a double value to an 4 | * int value. Enter the input as an integer whose last two digits represent the cents. 5 | * For example, the input 1156 represents 11 dollars and 56 cents. 6 | * 7 | * Created by Sven on 8/17/2018. 8 | */ 9 | package Chapter02; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0222_Financial_application_monetary_units { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter the input as an integer whose last two digits represent the cents, " + 17 | "for example, the input 1156 represents 11 dollars and 56 cents: "); 18 | int amount = input.nextInt(); 19 | int remainingAmount = amount; 20 | 21 | int numberOfOneDollars = remainingAmount / 100; 22 | remainingAmount = remainingAmount % 100; 23 | 24 | int numberOfQuarters = remainingAmount / 25; 25 | remainingAmount = remainingAmount % 25; 26 | 27 | int numberOfDimes = remainingAmount / 10; 28 | remainingAmount = remainingAmount % 10; 29 | 30 | int numberOfNickels = remainingAmount / 5; 31 | remainingAmount = remainingAmount % 5; 32 | 33 | int numberOfPennies = remainingAmount; 34 | 35 | System.out.println("Your amount " + amount / 100.0 + " consists of"); 36 | System.out.println(" " + numberOfOneDollars + " dollars"); 37 | System.out.println(" " + numberOfQuarters + " quarters "); 38 | System.out.println(" " + numberOfDimes + " dimes"); 39 | System.out.println(" " + numberOfNickels + " nickels"); 40 | System.out.println(" " + numberOfPennies + " pennies"); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Chapter02/Exercise0223_Cost_of_driving.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Cost of driving) Write a program that prompts the user to enter the distance to 3 | * drive, the fuel efficiency of the car in miles per gallon, and the price per gallon 4 | * then displays the cost of the trip. 5 | * 6 | * Here is a sample run: 7 | * Enter the driving distance: 900.5 8 | * Enter miles per gallon: 25.5 9 | * Enter price per gallon: 3.55 10 | * The cost of driving is $125.36 11 | * 12 | * Created by Sven on 8/17/2018. 13 | */ 14 | package Chapter02; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0223_Cost_of_driving { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter the driving distance: "); 22 | double drivingDistance = input.nextDouble(); 23 | System.out.print("Enter miles per gallon: "); 24 | double milesPerGallon = input.nextDouble(); 25 | System.out.print("Enter price per gallon: "); 26 | double pricePerGallon = input.nextDouble(); 27 | 28 | double cost = drivingDistance / milesPerGallon * pricePerGallon; 29 | System.out.println("The cost of driving is $" + cost); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0302_Game_multiply_three_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: multiply three numbers) The program in Listing 3.1, AdditionQuiz.java, 3 | * generates two integers and prompts the user to enter the product of these two integers. 4 | * Revise the program to generate three single-digit integers and prompt the user 5 | * to enter the multiplication of these three integers. 6 | * 7 | * Created by Sven on 8/18/2018. 8 | */ 9 | package Chapter03; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0302_Game_multiply_three_numbers { 14 | public static void main(String[] args) { 15 | int number1, number2, number3; 16 | // Method 1: Generate three single-digit integers 17 | // number1 = (int) (System.currentTimeMillis() % 10); 18 | // number2 = (int) (System.currentTimeMillis() / 7 % 10); 19 | // number3 = (int) (System.currentTimeMillis() / 70 % 10); 20 | 21 | // Method 2: Generate three single-digit integers 22 | number1 = (int) (Math.random() * 9 + 1); 23 | number2 = (int) (Math.random() * 9 + 1); 24 | number3 = (int) (Math.random() * 9 + 1); 25 | 26 | Scanner input = new Scanner(System.in); 27 | System.out.print("What is " + number1 + " * " + number2 + " * " + number3 + "? "); 28 | int answer = input.nextInt(); 29 | 30 | System.out.println(number1 + " * " + number2 + " * " + number3 + " = " + answer + " is " + 31 | (number1 * number2 * number3 == answer)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0303_Algebra_solve_2x2_linear_equations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Algebra: solve 2 * 2 linear equations) A linear equation can be solved using 3 | * Cramer's rule given in Programming Exercise 1.13. Write a program that prompts 4 | * the user to enter a, b, c, d, e, and f and displays the result. If ad - bc is 0, report 5 | * that "The equation has no solution." 6 | * 7 | * Enter a, b, c, d, e, f: 9.0 4.0 3.0 -5.0 -6.0 -21.0 8 | * x is -2.0 and y is 3.0 9 | * Enter a, b, c, d, e, f: 1.0 2.0 2.0 4.0 4.0 5.0 10 | * The equation has no solution 11 | * 12 | * Created by Sven on 8/18/2018. 13 | */ 14 | package Chapter03; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0303_Algebra_solve_2x2_linear_equations { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter a, b, c, d, e, f: "); 22 | double a = input.nextDouble(); 23 | double b = input.nextDouble(); 24 | double c = input.nextDouble(); 25 | double d = input.nextDouble(); 26 | double e = input.nextDouble(); 27 | double f = input.nextDouble(); 28 | 29 | if (a * d != b * c) { 30 | System.out.println("x is " + (e * d - b * f) / (a * d - b * c) 31 | + " and y is " + (a * f - e * c) / (a * d - b * c)); 32 | } else { 33 | System.out.println("The equation has no solution"); 34 | } 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0304_Random_month.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Random month) Write a program that randomly generates an integer between 1 3 | * and 12 and displays the English month names January, February, . . . , December 4 | * for the numbers 1, 2, . . . , 12, accordingly. 5 | * 6 | * Created by Sven on 8/18/2018. 7 | */ 8 | package Chapter03; 9 | 10 | public class Exercise0304_Random_month { 11 | public static void main(String[] args) { 12 | int monthNumber = (int) (Math.random() * 12 + 1); 13 | String monthName = ""; 14 | switch (monthNumber) { 15 | case 1: 16 | monthName = "January"; 17 | break; 18 | case 2: 19 | monthName = "February"; 20 | break; 21 | case 3: 22 | monthName = "March"; 23 | break; 24 | case 4: 25 | monthName = "April"; 26 | break; 27 | case 5: 28 | monthName = "May"; 29 | break; 30 | case 6: 31 | monthName = "June"; 32 | break; 33 | case 7: 34 | monthName = "July"; 35 | break; 36 | case 8: 37 | monthName = "August"; 38 | break; 39 | case 9: 40 | monthName = "September"; 41 | break; 42 | case 10: 43 | monthName = "October"; 44 | break; 45 | case 11: 46 | monthName = "November"; 47 | break; 48 | case 12: 49 | monthName = "December"; 50 | break; 51 | } 52 | System.out.println("The randomly generated integer is " + monthNumber + ", the month name is " + monthName); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0306_Health_application_BMI.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Health application: BMI) Revise Listing 3.4, ComputeAndInterpretBMI.java, to 3 | * let the user enter weight, feet, and inches. For example, if a person is 5 feet and 10 4 | * inches, you will enter 5 for feet and 10 for inches. 5 | * 6 | * Here is a sample run: 7 | * Enter weight in pounds: 140 8 | * Enter feet: 5 9 | * Enter inches: 10 10 | * BMI is 20.087702275404553 11 | * Normal 12 | * 13 | * Created by Sven on 8/22/2018. 14 | */ 15 | package Chapter03; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0306_Health_application_BMI { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | 23 | System.out.print("Enter weight in pounds: "); 24 | double weightInPounds = input.nextDouble(); 25 | 26 | System.out.print("Enter feet: "); 27 | double feet = input.nextDouble(); 28 | 29 | System.out.print("Enter inches: "); 30 | double inches = input.nextDouble(); 31 | 32 | double heightInInches = feet * 12 + inches; 33 | 34 | final double KILOGRAMS_PER_POUND = 0.45359237; // Constant 35 | final double METERS_PER_INCH = 0.0254; // Constant 36 | 37 | double weightInKilograms = weightInPounds * KILOGRAMS_PER_POUND; 38 | double heightInMeters = heightInInches * METERS_PER_INCH; 39 | double bmi = weightInKilograms / (heightInMeters * heightInMeters); 40 | 41 | System.out.println("BMI is " + bmi); 42 | if (bmi < 18.5) 43 | System.out.println("Underweight"); 44 | else if (bmi < 25) 45 | System.out.println("Normal"); 46 | else if (bmi < 30) 47 | System.out.println("Overweight"); 48 | else System.out.println("Obese"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0308_Sort_three_integers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sort three integers) Write a program that prompts the user to enter three integers 3 | * and display the integers in non-decreasing order. 4 | * 5 | * Created by Sven on 8/22/2018. 6 | */ 7 | package Chapter03; 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise0308_Sort_three_integers { 12 | public static void main(String[] args) { 13 | Scanner input = new Scanner(System.in); 14 | System.out.print("Enter three integers separated by spaces: "); 15 | int num1 = input.nextInt(); 16 | int num2 = input.nextInt(); 17 | int num3 = input.nextInt(); 18 | int temp; 19 | 20 | if (num1 > num2) { 21 | temp = num1; 22 | num1 = num2; 23 | num2 = temp; 24 | } 25 | 26 | if (num2 > num3) { 27 | temp = num2; 28 | num2 = num3; 29 | num3 = temp; 30 | } 31 | 32 | if (num1 > num2) { 33 | temp = num1; 34 | num1 = num2; 35 | num2 = temp; 36 | } 37 | 38 | System.out.println("The integers in non-decreasing order: " + num1 + " " + num2 + " " + num3); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0310_Game_addition_quiz.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: multiplication quiz) Listing 3.3, SubtractionQuiz.java, randomly generates 3 | * a subtraction question. Revise the program to randomly generate a multiplication 4 | * question with two integers less than 1000. 5 | * 6 | * Created by Sven on 8/22/2018. 7 | */ 8 | package Chapter03; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0310_Game_addition_quiz { 13 | public static void main(String[] args) { 14 | int number1 = (int) (Math.random() * 100 + 1); 15 | int number2 = (int) (Math.random() * 100 + 1); 16 | 17 | System.out.print("What is " + number1 + " + " + number2 + "? "); 18 | Scanner input = new Scanner(System.in); 19 | int answer = input.nextInt(); 20 | 21 | if (number1 + number2 == answer) 22 | System.out.println("You are correct!"); 23 | else { 24 | System.out.println("Your answer is wrong."); 25 | System.out.println(number1 + " + " + number2 + " should be " + (number1 + number2)); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0312_Palindrome_number.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Palindrome integer) Write a program that prompts the user to enter a three-digit 3 | * integer and determines whether it is a palindrome integer. An integer is palindrome 4 | * if it reads the same from right to left and from left to right. A negative integer is 5 | * treated the same as a positive integer. 6 | * 7 | * Here is a sample run of this program: 8 | * Enter a three-digit integer: 121 9 | * 121 is a palindrome 10 | * Enter a three-digit integer: 123 11 | * 123 is not a palindrome 12 | * 13 | * Created by Sven on 8/22/2018. 14 | */ 15 | package Chapter03; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0312_Palindrome_number { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter a three-digit integer: "); 23 | int originalNum = input.nextInt(); 24 | int lastDigit = originalNum % 10; 25 | int firstDigit = originalNum / 100; 26 | System.out.print(originalNum); 27 | System.out.println(lastDigit == firstDigit ? " is a palindrome" : " is not a palindrome"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0314_Game_heads_or_tails.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: heads or tails) Write a program that lets the user guess whether the flip of 3 | * a coin results in heads or tails. The program randomly generates an integer 0 or 1, 4 | * which represents head or tail. The program prompts the user to enter a guess, and 5 | * reports whether the guess is correct or incorrect. 6 | * 7 | * Created by Sven on 8/22/2018. 8 | */ 9 | package Chapter03; 10 | 11 | import java.util.Scanner; 12 | 13 | 14 | public class Exercise0314_Game_heads_or_tails { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Guess the result of a coin flip, Enter 0 for heads and 1 for tails: "); 18 | int userInput = input.nextInt(); 19 | 20 | // Little trick for ... 21 | System.out.print("Coin flipping "); 22 | for (int i = 0; i < 3; i++) { 23 | System.out.print("."); 24 | try { 25 | Thread.sleep(500); 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | 31 | int coinSide = (int) (Math.random() * 2); 32 | System.out.println(coinSide == 0 ? "\nIt is heads." : "\nIt is tails."); 33 | System.out.println(userInput == 0 ? "Your guess is heads." : "Your guess is tails."); 34 | System.out.println(userInput == coinSide ? "GOOD JOB!" : "TRY AGAIN!"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0316_Random_point.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Random point) Write a program that displays a random coordinate in a rectangle. 3 | * The rectangle is centred at (0, 0) with width 50 and height 150. 4 | * 5 | * Created by Sven on 8/23/2018. 6 | */ 7 | package Chapter03; 8 | 9 | public class Exercise0316_Random_point { 10 | public static void main(String[] args) { 11 | double x = Math.random() * 100 - 50; 12 | double y = Math.random() * 200 - 100; 13 | 14 | System.out.println("The randomly generated point: (" + x + ", " + y + ")"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0318_Cost_of_shipping.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Cost of shipping) A shipping company uses the following function to calculate the 3 | * cost (in dollars) of shipping based on the weight of the package (in pounds). 4 | * c(w)={ 5 | * 2.5, if 0 < w <= 2 6 | * 4.5, if 2 < w <= 4 7 | * 7.5, if 4 < w <= 10 8 | * 10.5, if 10 < w <= 20 9 | * 10 | * Write a program that prompts the user to enter the weight of the package and 11 | * display the shipping cost. If the weight is greater than 20, display a message "the 12 | * package cannot be shipped." 13 | * 14 | * Created by Sven on 8/23/2018. 15 | */ 16 | package Chapter03; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0318_Cost_of_shipping { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter the weight of the package (in pounds): "); 24 | double weight = input.nextDouble(); 25 | 26 | if (weight <= 0) { 27 | System.out.println("Enter a positive number."); 28 | } else if (weight <= 2) { 29 | System.out.println("The cost (in dollars): 2.5"); 30 | } else if (weight <= 4) { 31 | System.out.println("The cost (in dollars): 4.5"); 32 | } else if (weight <= 10) { 33 | System.out.println("The cost (in dollars): 7.5"); 34 | } else if (weight <= 20) { 35 | System.out.println("The cost (in dollars): 10.5"); 36 | } else if (weight <= 50) { 37 | System.out.println("It cannot be calculated because the function is not available."); 38 | } else { 39 | System.out.println("The package cannot be shipped."); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0319_Compute_the_perimeter_of_a_triangle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Compute the perimeter of a triangle) Write a program that reads three edges for a 3 | * triangle and computes the perimeter if the input is valid. Otherwise, display that the 4 | * input is invalid. The input is valid if the sum of every pair of two edges is greater 5 | * than the remaining edge. 6 | * 7 | * Created by Sven on 8/23/2018. 8 | */ 9 | package Chapter03; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0319_Compute_the_perimeter_of_a_triangle { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter three edges for a triangle (Separated by spaces): "); 17 | double edge1 = input.nextDouble(); 18 | double edge2 = input.nextDouble(); 19 | double edge3 = input.nextDouble(); 20 | 21 | if ((edge1 + edge2 > edge3) && (edge1 + edge3 > edge2) && (edge2 + edge3 > edge1)) { 22 | System.out.println("The perimeter is " + (edge1 + edge2 + edge3)); 23 | } else { 24 | System.out.println("The input is invalid."); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0320_Science_wind_chill_temperature.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Science: wind-chill temperature) Programming Exercise 2.17 gives a formula to 3 | * compute the wind-chill temperature. The formula is valid for temperatures in the 4 | * range between -58℉ and 41℉ and wind speed greater than or equal to 2. Write 5 | * a program that prompts the user to enter a temperature and a wind speed. The program 6 | * displays the wind-chill temperature if the input is valid; otherwise, it displays 7 | * a message indicating whether the temperature and/or wind speed is invalid. 8 | * 9 | * Created by Sven on 8/23/2018. 10 | */ 11 | package Chapter03; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0320_Science_wind_chill_temperature { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter the temperature in Fahrenheit between -58°F and 41°F: "); 19 | double ta = input.nextDouble(); 20 | if (ta < -58 || ta > 41) { 21 | System.out.println("Invalid input of the temperature."); 22 | System.exit(1); 23 | } 24 | System.out.print("Enter the wind speed (>=2) in miles per hour: "); 25 | double v = input.nextDouble(); 26 | if (v < 2) { 27 | System.out.println("Invalid input of the wind speed."); 28 | System.exit(1); 29 | } 30 | 31 | double twc = 35.74 + 0.6215 * ta - 35.75 * Math.pow(v, 0.16) + 0.4275 * ta * Math.pow(v, 0.16); 32 | System.out.println("The wind chill index is " + twc); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0322_Geometry_point_in_a_circle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: point in a circle?) Write a program that prompts the user to enter a 3 | * point (x, y) and checks whether the point is within the circle centered at (0, 0) with 4 | * radius 10. For example, (4, 5) is inside the circle and (9, 9) is outside the circle, as 5 | * shown in Figure 3.7a. 6 | * (Hint: A point is in the circle if its distance to (0, 0) is less than or equal to 10. 7 | * The formula for computing the distance is sqrt((x2 - x1)^2 + (y2 - y1)^2) Test your 8 | * program to cover all cases.) 9 | * 10 | * Two sample runs are shown below. 11 | * Enter a point with two coordinates: 4 5 12 | * Point (4.0, 5.0) is in the circle 13 | * Enter a point with two coordinates: 9 9 14 | * Point (9.0, 9.0) is not in the circle 15 | * 16 | * Created by Sven on 8/25/2018. 17 | */ 18 | package Chapter03; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0322_Geometry_point_in_a_circle { 23 | public static void main(String[] args) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter a point with two coordinates: "); 26 | double x = input.nextDouble(); 27 | double y = input.nextDouble(); 28 | 29 | double distance = Math.pow((Math.pow(x, 2) + Math.pow(y, 2)), 0.5); 30 | System.out.print("Point (" + x + ", " + y + ") is "); 31 | if (distance <= 10) { 32 | System.out.println("in the circle."); 33 | } else { 34 | System.out.println("not in the circle."); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0323_Geometry_point_in_a_rectangle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * ((Geometry: point in a rectangle?) Write a program that prompts the user to enter a 3 | * point (x, y) and checks whether the point is within the rectangle centred at (1, 1) 4 | * with width 10 and height 5. For example, (2, 2) is inside the rectangle and (6, 4) 5 | * is outside the rectangle, as shown in Figure 3.7b. (Hint: A point is in the rectangle 6 | * if its horizontal distance to (0, 0) is less than or equal to 10 / 2 and its vertical 7 | * distance to (0, 0) is less than or equal to 5.0 / 2. Test your program to cover all 8 | * cases.) Here are two sample runs. 9 | * 10 | * Here are two sample runs. 11 | * Enter a point with two coordinates: 2 2 12 | * Point (2.0, 2.0) is in the rectangle 13 | * Enter a point with two coordinates: 6 4 14 | * Point (6.0, 4.0) is not in the rectangle 15 | * 16 | * Created by Sven on 8/25/2018. 17 | */ 18 | package Chapter03; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0323_Geometry_point_in_a_rectangle { 23 | public static void main(String[] args) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter a point with two coordinates: "); 26 | double x = input.nextDouble(); 27 | double y = input.nextDouble(); 28 | boolean inRectangle = false; 29 | 30 | System.out.print("Point (" + x + ", " + y + ") is "); 31 | if (x <= 10 / 2 && x >= -10 / 2) { 32 | if (y <= 5 / 2 && y >= -5 / 2) { 33 | inRectangle = true; 34 | } 35 | } 36 | System.out.println(inRectangle ? "in the rectangle." : "not in the rectangle."); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0324_Game_pick_a_card.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: pick a card) Write a program that simulates picking a card from a deck 3 | * of 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4 | * Jack, Queen, King) and suit (Clubs, Diamonds, Hearts, Spades) of the card. 5 | * 6 | * Here is a sample run of the program: 7 | * The card you picked is Jack of Hearts 8 | * 9 | * Created by Sven on 8/25/2018. 10 | */ 11 | package Chapter03; 12 | 13 | public class Exercise0324_Game_pick_a_card { 14 | public static void main(String[] args) { 15 | int rankIndex = (int) (Math.random() * 13); 16 | String rankStr = ""; 17 | int suitIndex = (int) (Math.random() * 4); 18 | String suitStr = ""; 19 | 20 | switch (rankIndex) { 21 | case 0: 22 | rankStr = "Ace"; 23 | break; 24 | case 10: 25 | rankStr = "Jack"; 26 | break; 27 | case 11: 28 | rankStr = "Queen"; 29 | break; 30 | case 12: 31 | rankStr = "King"; 32 | break; 33 | default: 34 | rankStr = String.valueOf(rankIndex + 1); 35 | } 36 | 37 | switch (suitIndex) { 38 | case 0: 39 | suitStr = "Clubs"; 40 | break; 41 | case 1: 42 | suitStr = "Diamonds"; 43 | break; 44 | case 2: 45 | suitStr = "Hearts"; 46 | break; 47 | case 3: 48 | suitStr = "Spades"; 49 | } 50 | 51 | System.out.println("The card you picked is " + rankStr + " of " + suitStr); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0326_Use_the_operators.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Use the &&, || and ^ operators) Write a program that prompts the user to enter 3 | * an integer and determines whether it is divisible by 4 and 5, whether it is divisible 4 | * by 4 or 5, and whether it is divisible by 4 or 5 but not both. 5 | * 6 | * Here is a sample run of this program 7 | * Enter an integer: 10 8 | * Is 10 divisible by 5 and 6? false 9 | * Is 10 divisible by 5 or 6? true 10 | * Is 10 divisible by 5 or 6, but not both? true 11 | * 12 | * Created by Sven on 8/25/2018. 13 | */ 14 | package Chapter03; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0326_Use_the_operators { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter an integer: "); 22 | int number = input.nextInt(); 23 | 24 | boolean isDivAnd = (number % 5 == 0) && (number % 6 == 0); 25 | boolean isDivOr = (number % 5 == 0) || (number % 6 == 0); 26 | boolean isDivXor = (number % 5 == 0) ^ (number % 6 == 0); 27 | 28 | System.out.println("Is " + number + " divisible by 5 and 6? " + isDivAnd); 29 | System.out.println("Is " + number + " divisible by 5 or 6? " + isDivOr); 30 | System.out.println("Is " + number + " divisible by 5 or 6, but not both? " + isDivXor); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0327_Geometry_points_in_triangle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: points in triangle?) Suppose a right triangle is placed in a plane as 3 | * shown below. The right-angle point is placed at (0, 0), and the other two points 4 | * are placed at (200, 0) and (0, 100). Write a program that prompts the user to enter 5 | * a point with x- and y-coordinates and determines whether the point is inside the 6 | * triangle. 7 | * 8 | * Here are the sample runs: 9 | * Enter a point's x- and y-coordinates: 100.5 25.5 10 | * The point is in the triangle 11 | * Enter a point’s x- and y-coordinates: 100.5 50.5 12 | * The point is not in the triangle 13 | * 14 | * Created by Sven on 8/25/2018. 15 | */ 16 | package Chapter03; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0327_Geometry_points_in_triangle { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter a point's x- and y-coordinates: "); 24 | double x = input.nextDouble(); 25 | double y = input.nextDouble(); 26 | 27 | if ((x >= 0) && (y >= 0) && (x <= 200) && (y <= 100) && (y <= 100 - x / 2)) { 28 | System.out.println("The point is in the triangle"); 29 | } else { 30 | System.out.println("The point is not in the triangle"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0330_Current_time.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Current time) Revise Programming Exercise 2.8 to display the hour using a 3 | * 12-hour clock. 4 | * 5 | * Here is a sample run: 6 | * Enter the time zone offset to GMT: -5 7 | * The current time is 4:50:34 AM 8 | * 9 | * Created by Sven on 8/26/2018. 10 | */ 11 | package Chapter03; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0330_Current_time { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter the time zone offset to GMT: "); 19 | int timeZone = input.nextInt(); 20 | 21 | long totalMilliseconds = System.currentTimeMillis(); 22 | long totalSeconds = totalMilliseconds / 1000; 23 | long currentSecond = totalSeconds % 60; 24 | long totalMinutes = totalSeconds / 60; 25 | long currentMinute = totalMinutes % 60; 26 | long totalHours = totalMinutes / 60; 27 | long currentHour = (totalHours + timeZone) % 24; 28 | 29 | String currentStr = (currentHour >= 12) ? ((currentHour - 12) + ":" + currentMinute + ":" + currentSecond + " PM") : 30 | ((currentHour - 12) + ":" + currentMinute + ":" + currentSecond + " AM"); 31 | System.out.println("The current time is " + currentStr); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0333_Financial_compare_costs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial: compare costs) Suppose you shop for rice in two different packages. 3 | * You would like to write a program to compare the cost. The program prompts the 4 | * user to enter the weight and price of each package and displays the one with the 5 | * better price. 6 | * 7 | * Here is a sample run: 8 | * Enter weight and price for package 1: 50 24.59 9 | * Enter weight and price for package 2: 25 11.99 10 | * Package 2 has a better price. 11 | * Enter weight and price for package 1: 50 25 12 | * Enter weight and price for package 2: 25 12.5 13 | * Two packages have the same price. 14 | * 15 | * Created by Sven on 8/26/2018. 16 | */ 17 | package Chapter03; 18 | 19 | import java.util.Scanner; 20 | 21 | public class Exercise0333_Financial_compare_costs { 22 | public static void main(String[] args) { 23 | Scanner input = new Scanner(System.in); 24 | System.out.print("Enter weight and price for package 1: "); 25 | double weight1 = input.nextDouble(); 26 | double price1 = input.nextDouble(); 27 | double cost1 = price1 / weight1; 28 | 29 | System.out.print("Enter weight and price for package 2: "); 30 | double weight2 = input.nextDouble(); 31 | double price2 = input.nextDouble(); 32 | double cost2 = price2 / weight2; 33 | 34 | if (cost1 < cost2) { 35 | System.out.println("Package 1 has a better price."); 36 | } else if (cost1 > cost2) { 37 | System.out.println("Package 2 has a better price."); 38 | } else { 39 | System.out.println("The two packages have the same price."); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0334_Geometry_point_on_line_segment.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: point on line segment) Exercise 3.32 shows how to test whether a point 3 | * is on an unbounded line. Revise Exercise 3.32 to test whether a point is on a line 4 | * segment. Write a program that prompts the user to enter the three points for p0, 5 | * p1, and p2 and displays whether p2 is on the line segment from p0 to p1. 6 | * 7 | * Here are some sample runs: 8 | * Enter three points for p0, p1, and p2: 1 1 2.5 2.5 1.5 1.5 9 | * (1.5, 1.5) is on the line segment from (1.0, 1.0) to (2.5, 2.5) 10 | * Enter three points for p0, p1, and p2: 1 1 2 2 3.5 3.5 11 | * (3.5, 3.5) is not on the line segment from (1.0, 1.0) to (2.0, 2.0) 12 | * 13 | * Created by Sven on 8/26/2018. 14 | */ 15 | package Chapter03; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0334_Geometry_point_on_line_segment { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter three points for p0, p1, and p2: "); 23 | double x0 = input.nextDouble(); 24 | double y0 = input.nextDouble(); 25 | double x1 = input.nextDouble(); 26 | double y1 = input.nextDouble(); 27 | double x2 = input.nextDouble(); 28 | double y2 = input.nextDouble(); 29 | 30 | double conditionNum = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0); 31 | if ((conditionNum == 0) && ((x2 > x1) && (x2 < x0) || (x2 > x0) && (x2 < x1))) { 32 | System.out.println("(" + x2 + ", " + y2 + ") is on the line segment from " + 33 | "(" + x0 + ", " + y0 + ") to (" + x1 + ", " + y1 + ")"); 34 | } else { 35 | System.out.println("(" + x2 + ", " + y2 + ") is not on the line segment from " + 36 | "(" + x0 + ", " + y0 + ") to (" + x1 + ", " + y1 + ")"); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Chapter03/Exercise0335_Even_or_odd_number.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Even or odd number) Write a program that prompts the user to enter an integer and 3 | * displays whether the integer is an odd number or not. 4 | * 5 | * Here are the sample runs: 6 | * Enter an integer: 200 7 | * 200 is even number 8 | * Enter an integer: 211 9 | * 211 is odd number 10 | * 11 | * Created by Sven on 9/6/2018. 12 | */ 13 | package Chapter03; 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise0335_Even_or_odd_number { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | System.out.print("Enter an integer: "); 21 | int number = input.nextInt(); 22 | if (number % 2 == 0) { 23 | System.out.println(number + " is even number"); 24 | } else { 25 | System.out.println(number + " is odd number"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0401_Geometry_area_of_a_pentagon.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: area of a pentagon) Write a program that prompts the user to enter 3 | * the length from the center of a pentagon to a vertex and computes the area of the 4 | * pentagon, as shown in the following figure. 5 | * The formula for computing the area of a pentagon is Area = (5 * s^2) / (4 * tan(PI / 5)), where 6 | * s is the length of a side. The side can be computed using the formula s = 2r sin(PI / 5), where 7 | * r is the length from the center of a pentagon to a vertex. Round up two digits after the decimal point. 8 | * 9 | * Here is a sample run: 10 | * Enter the length from the center to a vertex: 5.5 11 | * The area of the pentagon is 71.92 12 | * 13 | * Created by Sven on 9/6/2018. 14 | */ 15 | package Chapter04; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0401_Geometry_area_of_a_pentagon { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter the length from the center to a vertex: "); 23 | double r = input.nextDouble(); 24 | double s = 2 * r * Math.sin(Math.PI / 5); 25 | double areaOfPentagon = (5 * Math.pow(s, 2)) / (4 * Math.tan(Math.PI / 5)); 26 | System.out.printf("The area of the pentagon is %.2f",areaOfPentagon); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0404_Geometry_area_of_a_hexagon.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: area of a hexagon) The area of a hexagon can be computed using the 3 | * following formula (s is the length of a side): 4 | * Area = (6 * s^2) / (4 * tan(PI/6)) 5 | * Write a program that prompts the user to enter the side of a hexagon and displays 6 | * its area. 7 | * 8 | * Here is a sample run: 9 | * Enter the side: 5.5 10 | * The area of the hexagon is 78.59 11 | * 12 | * Created by Sven on 10/6/2018. 13 | */ 14 | package Chapter04; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0404_Geometry_area_of_a_hexagon { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter the side: "); 22 | double side = input.nextDouble(); 23 | double area = (6 * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 6)); 24 | System.out.printf("The area of the hexagon is %.2f", area); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0405_Geometry_area_of_a_regular_polygon.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: area of a regular polygon) A regular polygon is an n-sided polygon in 3 | * which all sides are of the same length and all angles have the same degree (i.e., the 4 | * polygon is both equilateral and equiangular). The formula for computing the area 5 | * of a regular polygon is 6 | * Area = (n * s^2) / (4 * tan(PI / n)) 7 | * Here, s is the length of a side. Write a program that prompts the user to enter the 8 | * number of sides and their length of a regular polygon and displays its area. 9 | * 10 | * Here is a sample run: 11 | * Enter the number of sides: 5 12 | * Enter the side: 6.5 13 | * The area of the polygon is 72.69017017488385 14 | * 15 | * Created by Sven on 10/12/2018. 16 | */ 17 | package Chapter04; 18 | 19 | import java.util.Scanner; 20 | 21 | public class Exercise0405_Geometry_area_of_a_regular_polygon { 22 | public static void main(String[] args) { 23 | Scanner input = new Scanner(System.in); 24 | System.out.print("Enter the number of sides: "); 25 | int numberOfSides = input.nextInt(); 26 | System.out.print("Enter the side: "); 27 | double side = input.nextDouble(); 28 | double area = (numberOfSides * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / numberOfSides)); 29 | System.out.println("The area of the polygon is " + area); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0408_Find_the_character_of_an_ASCII_code.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the character of an ASCII code) Write a program that receives a character 3 | * and displays its ASCII code (an integer between 0 and 127). 4 | * 5 | * Here is a sample run: 6 | * Enter a character: E 7 | * The ASCII code for character E is 69 8 | * 9 | * Created by Sven on 10/22/2018. 10 | */ 11 | package Chapter04; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0408_Find_the_character_of_an_ASCII_code { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter a character: "); 19 | char character = input.next().charAt(0); 20 | int ascii = character; 21 | 22 | System.out.println("The ASCII code for character " + character + " is " + ascii); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0409_Find_the_Unicode_of_a_character.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the Unicode of a character) Write a program that receives a character and 3 | * displays its Unicode. 4 | * 5 | * Here is a sample run: 6 | * Enter a character: E 7 | * The Unicode for the character E is 69 8 | * 9 | * Created by Sven on 10/22/2018. 10 | */ 11 | package Chapter04; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0409_Find_the_Unicode_of_a_character { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter a character: "); 19 | char character = input.next().charAt(0); 20 | int unicode = character; 21 | 22 | System.out.println("The Unicode code for the character " + character + " is " + unicode); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0411_Binary_to_decimal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Binary to decimal) Write a program that prompts the user to enter binary digits 3 | * and displays its corresponding decimal value. 4 | * 5 | * Here are some sample runs: 6 | * Enter binary digits (0000 to 1111): 0111 7 | * The decimal value is 7 8 | * Enter binary digits (0000 to 1111): 1001 9 | * The decimal value is 9 10 | * Enter binary digits (0000 to 1111): 1100 11 | * The decimal value is 12 12 | * 13 | * Created by Sven on 10/22/2018. 14 | */ 15 | package Chapter04; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0411_Binary_to_decimal { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter binary digits (0000 to 1111): "); 23 | char[] chars = input.next().toCharArray(); 24 | int number = 0; 25 | 26 | for (int i = chars.length - 1; i >= 0; i--) { 27 | if (chars[i] == '1') { 28 | number += Math.pow(2, chars.length - 1 - i); 29 | } 30 | } 31 | // if (chars[3] == '1') { 32 | // number += Math.pow(2, 0); 33 | // } 34 | // if (chars[2] == '1') { 35 | // number += Math.pow(2, 1); 36 | // } 37 | // if (chars[1] == '1') { 38 | // number += Math.pow(2, 2); 39 | // } 40 | // if (chars[0] == '1') { 41 | // number += Math.pow(2, 3); 42 | // } 43 | 44 | System.out.println("The decimal value is " + number); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0412_Hex_to_binary.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Hex to binary) Write a program that prompts the user to enter a hex digit and 3 | * displays its corresponding binary number. For an incorrect input, display invalid 4 | * input. 5 | * 6 | * Here is a sample run: 7 | * Enter a hex digit: B 8 | * The binary value is 1011 9 | * Enter a hex digit: G 10 | * G is an invalid input 11 | * 12 | * Created by Sven on 10/22/2018. 13 | */ 14 | package Chapter04; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0412_Hex_to_binary { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter a hex digit: "); 22 | String chars = input.next().toUpperCase(); 23 | char character = chars.charAt(0); 24 | 25 | String digits = "0123456789ABCDEF"; 26 | int decVal = digits.indexOf(character); 27 | if (decVal == -1) { 28 | System.out.println(character + " is an invalid input"); 29 | } else { 30 | String binVal = Integer.toBinaryString(decVal); 31 | System.out.println("The binary value is " + binVal); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0413_Vowel_or_consonant.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Vowel or consonant?) Write a program that prompts the user to enter a letter and 3 | * check whether the letter is a vowel or consonant. For a nonletter input, display 4 | * invalid input. 5 | * 6 | * Here is a sample run: 7 | * Enter a letter: B 8 | * B is a consonant 9 | * Enter a letter: a 10 | * a 11 | * Enter a letter: # 12 | * # is an invalid input 13 | * 14 | * Created by Sven on 10/26/2018. 15 | */ 16 | package Chapter04; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0413_Vowel_or_consonant { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter a letter: "); 24 | char character = input.next().charAt(0); 25 | 26 | String chars = "aeiouAEIOUbcdfghjklmpqrstvwxyzBCDFGHJKLMPQRSTVWXY"; 27 | int position = chars.indexOf(character); 28 | if (position == -1) { 29 | System.out.println(character + " is an invalid input"); 30 | } else { 31 | System.out.print(character); 32 | System.out.println((position <= 9) ? " is a vowel" : " is a consonant"); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0414_Convert_letter_grade_to_number.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Convert letter grade to number) Write a program that prompts the user to enter a 3 | * letter grade A, B, C, D, or F and displays its corresponding numeric value 4, 3, 2, 4 | * 1, or 0. For other input, display invalid grade. 5 | * 6 | * Here is a sample run: 7 | * Enter a letter grade: B 8 | * The numeric value for grade B is 3 9 | * Enter a letter grade: T 10 | * T is an invalid grade 11 | * 12 | * Created by Sven on 10/26/2018. 13 | */ 14 | package Chapter04; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0414_Convert_letter_grade_to_number { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter a letter grade: "); 22 | char character = input.next().charAt(0); 23 | 24 | String chars = "ABCDF"; 25 | int position = chars.indexOf(character); 26 | if (position == -1) { 27 | System.out.println(character + " is an invalid grade"); 28 | } else { 29 | System.out.println("The numeric value for grade " + character + " is " + (4 - position)); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0415_Phone_key_pads.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Phone key pads) The international standard letter/number mapping found on the 3 | * telephone is shown below: 4 | * Write a program that prompts the user to enter a lowercase or uppercase letter and 5 | * displays its corresponding number. For a nonletter input, display invalid input. 6 | * 7 | * Enter a letter: A 8 | * The corresponding number is 2 9 | * Enter a letter: a 10 | * The corresponding number is 2 11 | * Enter a letter: + 12 | * + is an invalid input 13 | * 14 | * Created by Sven on 10/26/2018. 15 | */ 16 | package Chapter04; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0415_Phone_key_pads { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter a letter: "); 24 | char character = input.next().charAt(0); 25 | 26 | String chars = "ABCabcDEFdefGHIghiJKLjklMNOmnoPQRSpqrsTUVtuvWXYZwxyz"; 27 | int position = chars.indexOf(character); 28 | int number = -1; 29 | if (position >= 0 && position < 6) { 30 | number = 2; 31 | } else if (position >= 6 && position < 12) { 32 | number = 3; 33 | } else if (position >= 12 && position < 18) { 34 | number = 4; 35 | } else if (position >= 18 && position < 24) { 36 | number = 5; 37 | } else if (position >= 30 && position < 36) { 38 | number = 6; 39 | } else if (position >= 36 && position < 44) { 40 | number = 7; 41 | } else if (position >= 44 && position < 50) { 42 | number = 8; 43 | } else if (position >= 50 && position < 58) { 44 | number = 9; 45 | } 46 | 47 | if (number == -1) { 48 | System.out.println(character + " is an invalid input"); 49 | } else { 50 | System.out.println("The corresponding number is " + number); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0416_Random_character.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Random character) Write a program that displays a random lowercase letter using 3 | * the Math.random() method. 4 | * 5 | * Created by Sven on 10/26/2018. 6 | */ 7 | package Chapter04; 8 | 9 | public class Exercise0416_Random_character { 10 | public static void main(String[] args) { 11 | int randomNumber = (int) (Math.random() * 26 + 97); 12 | char character = (char) randomNumber; 13 | System.out.println("The generated random lowercase letter is " + character); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0417_Days_of_a_month.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Days of a month) Write a program that prompts the user to enter the year and the 3 | * first three letters of a month name (with the first letter in uppercase) and displays 4 | * the number of days in the month. If the input for month is incorrect, display a message 5 | * as presented in the following sample runs: 6 | * 7 | * Enter a year: 2001 8 | * Enter a month: Jan 9 | * Jan 2001 has 31 days 10 | * Enter a year: 2016 11 | * Enter a month: jan 12 | * jan is not a correct month name 13 | * 14 | * Created by Sven on 10/30/2018. 15 | */ 16 | package Chapter04; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0417_Days_of_a_month { 21 | public static void main(String[] args) { 22 | // Same as Exercise 0311 23 | Scanner input = new Scanner(System.in); 24 | System.out.print("Enter a year: "); 25 | int year = input.nextInt(); 26 | 27 | boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); 28 | 29 | System.out.print("Enter a month: "); 30 | String month = input.next(); 31 | switch (month) { 32 | case "Feb": 33 | System.out.println(isLeapYear ? (month + " " + year + " has 29 days") : (month + " " + year + " has 28 days")); 34 | case "Jan": 35 | case "Mar": 36 | case "May": 37 | case "Jul": 38 | case "Aug": 39 | case "Oct": 40 | case "Dec": 41 | System.out.println(month + " " + year + " has 31 days"); 42 | break; 43 | case "Apr": 44 | case "Jun": 45 | case "Sep": 46 | case "Nov": 47 | System.out.println(month + " " + year + " has 30 days"); 48 | break; 49 | default: 50 | System.out.println(month + " is not a correct month name"); 51 | break; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0419_Business_check_ISBN_10.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Business: check ISBN-10) Rewrite Programming Exercise 3.9 by entering the 3 | * ISBN number as a string. 4 | * 5 | * Created by Sven on 10/30/2018. 6 | */ 7 | package Chapter04; 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise0419_Business_check_ISBN_10 { 12 | public static void main(String[] args) { 13 | // The code can be optimized using "loop" in Chapter 5 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Enter the first 9 digits of an ISBN: "); 16 | String originalNum = input.next(); 17 | int d1 = originalNum.charAt(0) - 48; 18 | int d2 = originalNum.charAt(1) - 48; 19 | int d3 = originalNum.charAt(2) - 48; 20 | int d4 = originalNum.charAt(3) - 48; 21 | int d5 = originalNum.charAt(4) - 48; 22 | int d6 = originalNum.charAt(5) - 48; 23 | int d7 = originalNum.charAt(6) - 48; 24 | int d8 = originalNum.charAt(7) - 48; 25 | int d9 = originalNum.charAt(8) - 48; 26 | 27 | int d10 = (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11; 28 | 29 | System.out.println(d10 == 10 ? (originalNum + "X") : (originalNum + Integer.toString(d10))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0420_Process_a_string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Process a string) Write a program that prompts the user to enter a string and displays 3 | * its length and its last character. 4 | * 5 | * Created by Sven on 10/30/2018. 6 | */ 7 | package Chapter04; 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise0420_Process_a_string { 12 | public static void main(String[] args) { 13 | Scanner input = new Scanner(System.in); 14 | System.out.print("Enter a string: "); 15 | String string = input.nextLine(); 16 | System.out.println("The length of the string is " + string.length()); 17 | System.out.println("The last character of the string is " + string.charAt(string.length() - 1)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0422_Check_substring.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Check substring) Write a program that prompts the user to enter two strings, and 3 | * reports whether the second string is a substring of the first string. 4 | * 5 | * Enter string s1: ABCD 6 | * Enter string s2: BC 7 | * BC is a substring of ABCD 8 | * Enter string s1: ABCD 9 | * Enter string s2: BDC 10 | * BDC is not a substring of ABCD 11 | * 12 | * Created by Sven on 11/2/2018. 13 | */ 14 | package Chapter04; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0422_Check_substring { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter string s1: "); 22 | String str1 = input.nextLine(); 23 | System.out.print("Enter string s2: "); 24 | String str2 = input.nextLine(); 25 | 26 | System.out.println(str1.contains(str2) ? (str2 + " is a substring of " + str1) : (str2 + " is not a substring of " + str1)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0424_Enter_three_countries.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Enter three countries) Write a program that prompts the user to enter three countries 3 | * and displays them in descending order. 4 | * 5 | * Here is a sample run: 6 | * Enter the first country: Germany 7 | * Enter the second country: France 8 | * Enter the third country: Switzerland 9 | * The three countries in descending order are Switzerland 10 | * Germany France 11 | * 12 | * Created by Sven on 11/2/2018. 13 | */ 14 | package Chapter04; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0424_Enter_three_countries { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter the first country: "); 22 | String country1 = input.nextLine(); 23 | System.out.print("Enter the second country: "); 24 | String country2 = input.nextLine(); 25 | System.out.print("Enter the third country: "); 26 | String country3 = input.nextLine(); 27 | 28 | String temp; 29 | 30 | // This code can be optimized using Method 31 | if (country1.compareTo(country2) > 0) { 32 | temp = country1; 33 | country1 = country2; 34 | country2 = temp; 35 | } 36 | if (country2.compareTo(country3) > 0) { 37 | temp = country2; 38 | country3 = country2; 39 | country2 = temp; 40 | } 41 | if (country1.compareTo(country2) > 0) { 42 | temp = country1; 43 | country1 = country2; 44 | country2 = temp; 45 | } 46 | System.out.println("The three countries in descending order are " + country1 + country2 + country3); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Chapter04/Exercise0425_Generate_vehicle_plate_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Generate vehicle plate numbers) Assume that a vehicle plate number consists of 3 | * three uppercase letters followed by four digits. Write a program to generate a plate 4 | * number. 5 | * Created by Sven on 11/2/2018. 6 | */ 7 | package Chapter04; 8 | 9 | public class Exercise0425_Generate_vehicle_plate_numbers { 10 | public static void main(String[] args) { 11 | StringBuilder vehiclePlateNumber = new StringBuilder(); 12 | vehiclePlateNumber.append((char) (Math.random() * 26 + 'A')); 13 | vehiclePlateNumber.append((char) (Math.random() * 26 + 'A')); 14 | vehiclePlateNumber.append((char) (Math.random() * 26 + 'A')); 15 | vehiclePlateNumber.append((char) (Math.random() * 10 + '0')); 16 | vehiclePlateNumber.append((char) (Math.random() * 10 + '0')); 17 | vehiclePlateNumber.append((char) (Math.random() * 10 + '0')); 18 | vehiclePlateNumber.append((char) (Math.random() * 10 + '0')); 19 | System.out.println("The randomly generated vehicle plate number is " + vehiclePlateNumber); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0501_Pass_or_fail.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Pass or fail) Write a program that prompts a student to enter a Java score. If the 3 | * score is greater or equal to 60, display “you pass the exam”; otherwise, display “you 4 | * don’t pass the exam”. Your program ends with input -1. 5 | * 6 | * Here is a sample run: 7 | * Enter your score: 80 8 | * You pass the exam. 9 | * Enter your score: 59 10 | * You don't pass the exam. 11 | * Enter your score: −1 12 | * No numbers are entered except 0 13 | * 14 | * Created by Sven on 11/8/2018. 15 | */ 16 | package Chapter05; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0501_Pass_or_fail { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | int score = 0; 24 | while (score != -1) { 25 | System.out.print("Enter your score: "); 26 | score = input.nextInt(); 27 | if (score == -1) { 28 | System.out.println("No numbers are entered except 0"); 29 | break; 30 | } else if (score < 0) { 31 | System.out.println("Negative input, please check again."); 32 | } else if (score > 100) { 33 | System.out.println("Score won't exceed 100"); 34 | } else if (score >= 60) { 35 | System.out.println("You pass the exam."); 36 | } else { 37 | System.out.println("You fail the exam."); 38 | } 39 | } 40 | System.out.println(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0503_Conversion_from_Celsius_to_Fahrenheit.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Conversion from Cº to Fº) Write a program that displays the following table (note 3 | * that fahrenheit = celsius * 9/5 + 32): 4 | * 5 | * Celsius Fahrenheit 6 | * 0 32.0 7 | * 2 35.6 8 | * ... 9 | * 98 208.4 10 | * 100 212.0 11 | * 12 | * Created by Sven on 1/16/2019. 13 | */ 14 | package Chapter05; 15 | 16 | public class Exercise0503_Conversion_from_Celsius_to_Fahrenheit { 17 | public static void main(String[] args) { 18 | double celsius, fahrenheit; 19 | System.out.println("Celsius Fahrenheit"); 20 | for (int count = 0; count <= 100; count += 2) { 21 | celsius = count; 22 | fahrenheit = celsius * 9 / 5 + 32; 23 | System.out.printf("%-3.0f%17.1f\n", celsius, fahrenheit); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0504_Conversion_from_inch_to_centimeter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Conversion from inch to centimeter) Write a program that displays the following 3 | * table (note that 1 inch is 2.54 centimeters): 4 | * Inches Centimetres 5 | * 1 2.54 6 | * 2 5.08 7 | * ... 8 | * 9 22.86 9 | * 10 25.4 10 | * 11 | * Created by Sven on 1/16/2019. 12 | */ 13 | package Chapter05; 14 | 15 | public class Exercise0504_Conversion_from_inch_to_centimeter { 16 | public static void main(String[] args) { 17 | int inches = 0; 18 | double centimeters = 0.0; 19 | System.out.println("Inches Centimetres"); 20 | for (; inches <= 10; inches++) { 21 | centimeters = (double) inches * 2.54; 22 | System.out.printf("%-9d%.2f\n", inches, centimeters); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0505_Conversion_from_C_to_F_and_F_to_C.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Conversion from Cº to Fº and Fº to Cº) Write a program that displays the following 3 | * two tables side by side: 4 | * Celsius Fahrenheit | Fahrenheit Celsius 5 | * 0 32.000 | 20 −6.667 6 | * 2 35.600 | 25 −3.889 7 | * ... 8 | * 98 208.400 | 265 129.444 9 | * 100 212.000 | 270 132.222 10 | * 11 | * Created by Sven on 1/16/2019. 12 | */ 13 | package Chapter05; 14 | 15 | public class Exercise0505_Conversion_from_C_to_F_and_F_to_C { 16 | public static void main(String[] args) { 17 | double celsius1, fahrenheit1, celsius2, fahrenheit2; 18 | System.out.println("Celsius Fahrenheit | Fahrenheit Celsius"); 19 | for (int count = 0; count <= 100; count += 2) { 20 | celsius1 = count; 21 | fahrenheit2 = 20 + count / 2 * 5; 22 | fahrenheit1 = celsius1 * 9 / 5 + 32; 23 | celsius2 = (fahrenheit2 - 32) / 9 * 5; 24 | System.out.printf("%-3.0f%17.3f | %-3.0f%17.3f\n", celsius1, fahrenheit1, fahrenheit2, celsius2); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0506_Conversion_from_square_meter_to_ping.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Conversion from square meter to ping) Write a program that displays the following 3 | * two tables side by side (note that 1 ping = 3.305 square meters): 4 | * Ping Square meter | Square meter Ping 5 | * 10 33.050 | 30 9.077 6 | * 15 49.575 | 35 10.590 7 | * ... 8 | * 75 247.875 | 95 28.744 9 | * 80 264.400 | 100 30.257 10 | * 11 | * Created by Sven on 1/16/2019. 12 | */ 13 | package Chapter05; 14 | 15 | public class Exercise0506_Conversion_from_square_meter_to_ping { 16 | public static void main(String[] args) { 17 | double ping1, squareMeter1, ping2, squareMeter2; 18 | System.out.println("Celsius Fahrenheit | Fahrenheit Celsius"); 19 | for (int count = 0; count <= 14; count++) { 20 | ping1 = count * 5 + 10; 21 | squareMeter1 = 3.305 * ping1; 22 | squareMeter2 = count * 5 + 30; 23 | ping2 = squareMeter2 / 3.305; 24 | System.out.printf("%-3.0f%17.3f | %-3.0f%17.3f\n", ping1, squareMeter1, squareMeter2, ping2); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0507_Financial_application_compute_future_tuition.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: compute future tuition) Suppose that the tuition for a university 3 | * is $10,000 this year and increases 6% every year. In one year, the tuition 4 | * will be $10,600. Write a program that computes the tuition in ten years and the total 5 | * cost of four years' worth of tuition after the tenth year. 6 | * 7 | * Created by Sven on 1/16/2019. 8 | */ 9 | package Chapter05; 10 | 11 | public class Exercise0507_Financial_application_compute_future_tuition { 12 | public static void main(String[] args) { 13 | double tuition = 10000; 14 | double fourYearsWorth = 0; 15 | for (int i = 0; i < 14; i++) { 16 | tuition *= 1.06; 17 | 18 | if (i == 10) { 19 | System.out.println(""); 20 | } 21 | if (i >= 11) { 22 | fourYearsWorth += tuition; 23 | } 24 | 25 | if (i == 0 || i == 10) { 26 | System.out.printf("The tuition in %2d year is $%,.3f\n", (i + 1), tuition); 27 | } else { 28 | System.out.printf("%17d year is $%,.3f\n", (i + 1), tuition); 29 | } 30 | } 31 | System.out.printf("The cost of four years' worth of tuition after the tenth year is $%,.3f", fourYearsWorth); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0508_Find_the_highest_score.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the highest score) Write a program that prompts the user to enter the number 3 | * of students and each student’s name and score, and finally displays the name of 4 | * the student with the highest score. Use the next() method in the Scanner class 5 | * to read a name, rather than using the nextLine() method. 6 | * 7 | * Created by Sven on 1/16/2019. 8 | */ 9 | package Chapter05; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0508_Find_the_highest_score { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter the number of students: "); 17 | int numberOfStudents = input.nextInt(); 18 | 19 | double highestScore = 0, score = 0; 20 | String studentWithHighest = "", studentName = ""; 21 | for (int i = 0; i < numberOfStudents; i++) { 22 | System.out.print("Enter the student’s name and score (eg. Jack 95): "); 23 | studentName = input.next(); 24 | score = input.nextDouble(); 25 | 26 | if (i == 0) { 27 | highestScore = score; 28 | studentWithHighest = studentName; 29 | } 30 | 31 | if (score > highestScore) { 32 | highestScore = score; 33 | studentWithHighest = studentName; 34 | } else if (score == highestScore) { 35 | studentWithHighest += ", " + studentName; 36 | } 37 | } 38 | System.out.println("The highest score: " + highestScore); 39 | System.out.println("The student with highest score: " + studentWithHighest); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0510_Find_numbers_divisible_by_3_and_4.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find numbers divisible by 3 and 4) Write a program that displays all the numbers 3 | * from 100 to 1,000, ten per line, that are divisible by 3 and 4. Numbers are separated 4 | * by exactly one space. 5 | * 6 | * Created by Sven on 3/8/2019. 7 | */ 8 | package Chapter05; 9 | 10 | public class Exercise0510_Find_numbers_divisible_by_3_and_4 { 11 | public static void main(String[] args) { 12 | int counter = 0; 13 | for (int i = 100; i <= 1000; i++) { 14 | if (i % 3 == 0 && i % 4 == 0) { 15 | System.out.print(i + "\t"); 16 | counter++; 17 | if (counter % 10 == 0) { 18 | System.out.println(); 19 | } 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0511_Find_numbers_divisible_by_3_or_4_but_not_both.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find numbers divisible by 3 or 4, but not both) Write a program that displays all 3 | * the numbers from 100 to 200, ten per line, that are divisible by 3 or 4, but not both. 4 | * Numbers are separated by exactly one space. 5 | * 6 | * Created by Sven on 3/8/2019. 7 | */ 8 | package Chapter05; 9 | 10 | public class Exercise0511_Find_numbers_divisible_by_3_or_4_but_not_both { 11 | public static void main(String[] args) { 12 | int counter = 0; 13 | for (int i = 100; i <= 200; i++) { 14 | if ((i % 3 == 0 || i % 4 == 0) && (!(i % 3 == 0 && i % 4 == 0))) { 15 | System.out.print(i + "\t"); 16 | counter++; 17 | if (counter % 10 == 0) { 18 | System.out.println(); 19 | } 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0512_Find_the_smallest_n_such_that_n3_bigger_than_12000.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the smallest n such that n^3 > 12,000) Use a while loop to find the smallest 3 | * integer n such that n3 is greater than 12,000. 4 | * 5 | * Created by Sven on 3/19/2019. 6 | */ 7 | package Chapter05; 8 | 9 | public class Exercise0512_Find_the_smallest_n_such_that_n3_bigger_than_12000 { 10 | public static void main(String[] args) { 11 | int num = 0; 12 | while (Math.pow(num, 3) < 12000) { 13 | num++; 14 | } 15 | System.out.println(num + " is the smallest number such that n^3 > 12,000"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0513_Find_the_largest_n_such_that_n2_smaller_than_12000.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the largest n such that n2 < 12,000) Use a while loop to find the largest 3 | * integer n such that n2 is less than 12,000. 4 | * 5 | * Created by Sven on 3/19/2019. 6 | */ 7 | package Chapter05; 8 | 9 | public class Exercise0513_Find_the_largest_n_such_that_n2_smaller_than_12000 { 10 | public static void main(String[] args) { 11 | int num = 0; 12 | while (Math.pow(num, 2) < 12000) { 13 | num++; 14 | } 15 | num--; 16 | System.out.println(num + " is the largest number such that n^2 < 12,000"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0514_Compute_the_greatest_common_divisor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Compute the greatest common divisor) Another solution for Listing 5.9 to find the 3 | * greatest common divisor of two integers n1 and n2 is as follows: First find d to be 4 | * the minimum of n1 and n2, then check whether d, d–1, d–2, …, 2, or 1 is a divisor 5 | * for both n1 and n2 in this order. The first such common divisor is the greatest 6 | * common divisor for n1 and n2. Write a program that prompts the user to enter two 7 | * positive integers and displays the gcd. 8 | * 9 | * Created by Sven on 3/19/2019. 10 | */ 11 | package Chapter05; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0514_Compute_the_greatest_common_divisor { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter two positive number: "); 19 | int n1 = input.nextInt(); 20 | int n2 = input.nextInt(); 21 | 22 | int d = (n1 <= n2) ? n1 : n2; 23 | 24 | while (d > 0) { 25 | if (n1 % d == 0 && n2 % d == 0) { 26 | break; 27 | } 28 | d--; 29 | } 30 | 31 | System.out.println("GCD of " + n1 + " and " + n2 + " is " + d); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0515_Display_the_ASCII_character_table.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display the ASCII character table) Write a program that prints the characters in 3 | * the ASCII character table from ! to ~. Display 10 characters per line. The ASCII 4 | * table is given in Appendix B. Characters are separated by exactly one space. 5 | * 6 | * Created by Sven on 3/19/2019. 7 | */ 8 | package Chapter05; 9 | 10 | public class Exercise0515_Display_the_ASCII_character_table { 11 | public static void main(String[] args) { 12 | for (int i = '!', counter = 1; i <= '~'; i++) { 13 | counter++; 14 | System.out.print((counter % 10 != 0) ? (char) i + " " : (char) i + "\n"); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0516_Find_the_factors_of_an_integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the factors of an integer) Write a program that reads an integer and displays 3 | * all its smallest factors in an increasing order. For example, if the input integer is 4 | * 120, the output should be as follows: 2, 2, 2, 3, 5. 5 | * 6 | * Created by Sven on 3/19/2019. 7 | */ 8 | package Chapter05; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0516_Find_the_factors_of_an_integer { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Enter a number: "); 16 | int num = input.nextInt(); 17 | int factor = 2; 18 | 19 | while (factor <= num) { 20 | if (num % factor == 0) { 21 | System.out.print(factor + " "); 22 | num /= factor; 23 | } else { 24 | factor++; 25 | } 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0517_Display_pyramid.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display pyramid) Write a program that prompts the user to enter an integer from 3 | * 1 to 15 and displays a pyramid, as shown in the following sample run: 4 | * 5 | * Enter the number of lines: 7 6 | * 7 6 5 4 3 2 1 2 3 4 5 6 7 7 | * 6 5 4 3 2 1 2 3 4 5 6 8 | * 5 4 3 2 1 2 3 4 5 9 | * 4 3 2 1 2 3 4 10 | * 3 2 1 2 3 11 | * 2 1 2 12 | * 1 13 | * 14 | * Created by Sven on 3/19/2019. 15 | */ 16 | package Chapter05; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0517_Display_pyramid { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter the number of lines: "); 24 | int numOfLines = input.nextInt(); 25 | int number = numOfLines; 26 | 27 | while (numOfLines >= 1) { 28 | number = numOfLines; 29 | for (; number > 1; number--) { 30 | System.out.print(number + " "); 31 | } 32 | for (; number <= numOfLines; number++) { 33 | System.out.print(number + " "); 34 | } 35 | numOfLines--; 36 | System.out.println(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0519_Display_numbers_in_a_pyramid_pattern.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display numbers in a pyramid pattern) Write a nested for loop that prints the 3 | * following output: 4 | * 1 5 | * 1 3 1 6 | * 1 3 9 3 1 7 | * 1 3 9 27 9 3 1 8 | * 1 3 9 27 81 27 9 3 1 9 | * 1 3 9 27 81 243 81 27 9 3 1 10 | * 1 3 9 27 81 243 729 243 81 27 9 3 1 11 | * 1 3 9 27 81 243 729 2187 729 243 81 27 9 3 1 12 | * Created by Sven on 3/21/2019. 13 | */ 14 | package Chapter05; 15 | 16 | public class Exercise0519_Display_numbers_in_a_pyramid_pattern { 17 | public static void main(String[] args) { 18 | int numOfLines = 8; 19 | for (int i = 0; i < numOfLines; i++) { 20 | for (int j = numOfLines - i - 1; j > 0; j--) { 21 | System.out.print(" "); 22 | } 23 | for (int j = 0; j <= i; j++) { 24 | if (j==0){ 25 | System.out.printf("%-1.0f", Math.pow(3, j)); 26 | }else { 27 | System.out.printf("%5.0f", Math.pow(3, j));} 28 | } 29 | for (int j = i - 1; j >= 0; j--) { 30 | System.out.printf("%5.0f", Math.pow(3, j)); 31 | } 32 | System.out.println(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0520_Display_prime_number_between_2_and_1200.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display prime numbers between 2 and 1,200) Modify Listing 5.15 to display all 3 | * the prime numbers between 2 and 1,200, inclusive. Display eight prime numbers 4 | * per line. Numbers are separated by exactly one space. 5 | * 6 | * Created by Sven on 3/21/2019. 7 | */ 8 | package Chapter05; 9 | 10 | public class Exercise0520_Display_prime_number_between_2_and_1200 { 11 | public static void main(String[] args) { 12 | final int NUMBER_OF_PRIMES_PER_LINE = 8; // Display 8 per line 13 | int count = 0; // Count the number of prime numbers 14 | int number = 2; // A number to be tested for primeness 15 | 16 | System.out.println("The prime numbers between [2,1,200] are \n"); 17 | 18 | // Repeatedly find prime numbers 19 | while (number <= 1200) { 20 | // Assume the number is prime 21 | boolean isPrime = true; // Is the current number prime? 22 | 23 | // Test if number is prime 24 | for (int divisor = 2; divisor <= number / 2; divisor++) { 25 | if (number % divisor == 0) { // If true, number is not prime 26 | isPrime = false; // Set isPrime to false 27 | break; // Exit the for loop 28 | } 29 | } 30 | 31 | // Print the prime number and increase the count 32 | if (isPrime) { 33 | count++; // Increase the count 34 | 35 | System.out.printf("%5d", number); 36 | if (count % NUMBER_OF_PRIMES_PER_LINE == 0) { 37 | // Print the number and advance to the new line 38 | System.out.println(); 39 | } 40 | } 41 | 42 | // Check if the next number is prime 43 | number++; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0523_Demonstrate_cancellation_errors.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Demonstrate cancellation errors) A cancellation error occurs when you are 3 | * manipulating a very large number with a very small number. The large number 4 | * may cancel out the smaller number. For example, the result of 100000000.0 + 5 | * 0.000000001 is equal to 100000000.0. To avoid cancellation errors and obtain 6 | * more accurate results, carefully select the order of computation. For example, in 7 | * computing the following summation, you will obtain more accurate results by 8 | * computing from right to left rather than from left to right: 9 | * 1 + 1/2 + 1/3 + ... + 1/n 10 | * Write a program that compares the results of the summation of the preceding series, 11 | * computing from left to right and from right to left with n = 50000. 12 | * 13 | * Created by Sven on 3/21/2019. 14 | */ 15 | package Chapter05; 16 | 17 | public class Exercise0523_Demonstrate_cancellation_errors { 18 | public static void main(String[] args) { 19 | int n = 50000; 20 | double result1 = 0, result2 = 0; 21 | for (int i = 1; i <= n; i++) { 22 | result1 += 1.0 / i; 23 | } 24 | System.out.println("Computing from left to right: " + result1); 25 | 26 | for (int i = n; i >= 1; i--) { 27 | result2 += 1.0 / i; 28 | } 29 | System.out.println("Computing from right to left: " + result2); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0524_Sum_a_series.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sum a series) Write a program to compute the following summation: 3 | * 1/3 + 3/5 + 5/7 + ... + 97/99 4 | * 5 | * Created by Sven on 3/21/2019. 6 | */ 7 | package Chapter05; 8 | 9 | public class Exercise0524_Sum_a_series { 10 | public static void main(String[] args) { 11 | double result = 0; 12 | for (int i = 1; i <= 97; i++) { 13 | result += 1.0 * i / (i + 2); 14 | } 15 | System.out.println("The result for 1/3 + 3/5 + 5/7 + ... + 97/99 is " + result); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0525_Compute_PI.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Compute p) You can approximate p by using the following summation: 3 | * PI = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - ... + ((-)^(i+1))/(2i - 1)) 4 | * Write a program that displays the p value for i = 10000, 20000, …, and 100000. 5 | * 6 | * Created by Sven on 3/21/2019. 7 | */ 8 | package Chapter05; 9 | 10 | public class Exercise0525_Compute_PI { 11 | public static void main(String[] args) { 12 | double PI = 1.0; 13 | for (int i = 2; i <= 100000; i++) { 14 | PI += Math.pow(-1, i + 1) / (2 * i - 1.0D); 15 | if (i % 10000 == 0) { 16 | System.out.println("i = " + i + "\tPI = " + 4.0 * PI); 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0526_Compute_e.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Compute e) You can approximate e using the following summation: 3 | * e = 1 + 1/1! + 1/2! + 1/3! + ... + 1/i! 4 | * Write a program that displays the e value for i = 10000, 20000, …, and 100000. 5 | * (Hint: Because i! = i * (i - 1) * ... * 2 * 1, then 1/i! is 1/(i(i-1)!) 6 | * Initialize e and item to be 1, and keep adding a new item to e. The new item is 7 | * the previous item divided by i, for i >= 2.) 8 | * 9 | * Created by Sven on 3/23/2019. 10 | */ 11 | package Chapter05; 12 | 13 | public class Exercise0526_Compute_e { 14 | public static void main(String[] strings) { 15 | double e = 1.0; 16 | double item = 1.0; 17 | for (int i = 2; i <= 100000; i++) { 18 | item /= (double) i; 19 | e += item; 20 | if (i % 10000 == 0) { 21 | System.out.println("i = " + i + "\te = " + e); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0527_Display_leap_years.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display leap years) Write a program that displays all the leap years, ten per line, 3 | * from 2014 to 2114, separated by exactly one space. Also display the number of 4 | * leap years in this period. 5 | * 6 | * Created by Sven on 3/23/2019. 7 | */ 8 | package Chapter05; 9 | 10 | public class Exercise0527_Display_leap_years { 11 | public static void main(String[] args) { 12 | System.out.println("The leap year between 2014 and 2114"); 13 | for (int i = 2014, counter = 1; i < 2114; i++) { 14 | if ((i % 400 == 0) || ((i % 4 == 0) && (i % 100 != 0))) { 15 | System.out.print(i + " "); 16 | if (counter % 10 == 0) { 17 | System.out.println(); 18 | } 19 | counter++; 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0530_Financial_application_compound_value.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: compound value) Suppose you save $100 each month 3 | * in a savings account with annual interest rate 3.75%. The monthly interest rate 4 | * is 0.0375 / 12 = 0.003125. After the first month, the value in the account 5 | * becomes 6 | * 100 * (1 + 0.003125) = 100.3125 7 | * After the second month, the value in the account becomes 8 | * 100 + 100.3125) * (1 + 0.003125) = 200.938 9 | * After the third month, the value in the account becomes 10 | * (100 + 200.938) * (1 + 0.003125) = 301.878 11 | * and so on. 12 | * Write a program that prompts the user to enter an amount (e.g., 100), the annual 13 | * interest rate (e.g., 3.75), and the number of months (e.g., 6) and displays the 14 | * amount in the savings account after the given month. 15 | * 16 | * Created by Sven on 3/23/2019. 17 | */ 18 | package Chapter05; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0530_Financial_application_compound_value { 23 | public static void main(String[] strings) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter amount to save each month: "); 26 | double monthlySavings = input.nextDouble(); 27 | System.out.print("Enter annual interest: "); 28 | double annualInterestRate = input.nextDouble(); 29 | System.out.print("Enter number of months: "); 30 | int numberOfMonths = input.nextInt(); 31 | 32 | double monthlyInterestRate = annualInterestRate / 1200.0D; 33 | double accountValue = monthlySavings * (1.0D + monthlyInterestRate); 34 | 35 | for (int i = 1; i < numberOfMonths; i++) { 36 | accountValue = (accountValue + monthlySavings) * (1.0D + monthlyInterestRate); 37 | } 38 | System.out.println("After month #" + numberOfMonths + ", the account value is " + accountValue); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0532_Game_lottery.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: lottery) Revise Listing 3.8, Lottery.java, to generate a lottery of a two-digit 3 | * number. The two digits in the number are distinct. (Hint: Generate the first digit. 4 | * Use a loop to continuously generate the second digit until it is different from the 5 | * first digit.) 6 | * 7 | * Created by Sven on 3/26/2019. 8 | */ 9 | package Chapter05; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0532_Game_lottery { 14 | public static void main(String[] args) { 15 | // Prompt the user to enter a guess 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter your lottery pick (two digits): "); 18 | int guess = input.nextInt(); 19 | 20 | // Get digits from lottery 21 | int lotteryDigit1 = (int) (Math.random() * 10); 22 | int lotteryDigit2; 23 | do { 24 | lotteryDigit2 = (int) (Math.random() * 10); 25 | } while (lotteryDigit1 == lotteryDigit2); 26 | int lottery = lotteryDigit1 * 10 + lotteryDigit2; 27 | 28 | // Get digits from guess 29 | int guessDigit1 = guess / 10; 30 | int guessDigit2 = guess % 10; 31 | 32 | System.out.println("The lottery number is " + lottery); 33 | 34 | // Check the guess 35 | if (guess == lottery) 36 | System.out.println("Exact match: you win $10,000"); 37 | else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2) 38 | System.out.println("Match all digits: you win $3,000"); 39 | else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1 40 | || guessDigit2 == lotteryDigit2) 41 | System.out.println("Match one digit: you win $1,000"); 42 | else System.out.println("Sorry, no match"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0533_Perfect_number.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Perfect number) A positive integer is called a perfect number if it is equal to the 3 | * sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect 4 | * number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There 5 | * are four perfect numbers 6 10,000. Write a program to find all these four numbers. 6 | * 7 | * Created by Sven on 3/27/2019. 8 | */ 9 | package Chapter05; 10 | 11 | public class Exercise0533_Perfect_number { 12 | public static void main(String[] args) { 13 | System.out.println("The four perfect numbers<10,000: "); 14 | for (int i = 1; i <= 10000; i++) { 15 | int number = i; 16 | int divisor = i; 17 | int sumOfDivisors = 0; 18 | while (divisor > 0) { 19 | if (number % divisor == 0 && number != divisor) { 20 | sumOfDivisors += divisor; 21 | } 22 | divisor--; 23 | } 24 | if (number == sumOfDivisors) { 25 | System.out.print(number + " "); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0535_Summation.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Summation) Write a program to compute the following summation: 3 | * 1/(1+sqrt(2))+ 1/(sqrt(2)+sqrt(3))+ 1/(sqrt(3)+sqrt(4))+ ... + 1/(sqrt(999)+sqrt(1000)) 4 | * 5 | * Created by Sven on 4/14/2019. 6 | */ 7 | package Chapter05; 8 | 9 | public class Exercise0535_Summation { 10 | public static void main(String[] args) { 11 | double sum = 0.0; 12 | for (int i = 1; i <= 999; i++) { 13 | sum += 1 / (Math.sqrt(i) + Math.sqrt(i + 1)); 14 | } 15 | System.out.println("Sum in the order that from left to right: " + sum); 16 | 17 | sum = 0.0; 18 | for (int i = 999; i >= 1; i--) { 19 | sum += 1 / (Math.sqrt(i) + Math.sqrt(i + 1)); 20 | } 21 | System.out.print("Sum in the order that from right to left: " + sum); 22 | System.out.println(" (More accurate to sum from the smaller one to the bigger one when adding a series)"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0536_Business_application_checking_ISBN.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Business application: checking ISBN) Use loops to simplify Programming 3 | * Exercise 3.9. 4 | * 5 | * Created by Sven on 4/14/2019. 6 | */ 7 | package Chapter05; 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise0536_Business_application_checking_ISBN { 12 | public static void main(String[] args) { 13 | Scanner input = new Scanner(System.in); 14 | System.out.print("Enter the first 9 digits of an ISBN as integer: "); 15 | int originalNum = input.nextInt(); 16 | int remainNum = originalNum; 17 | 18 | // int d9 = remainNum % 10; 19 | // remainNum /= 10; 20 | // int d8 = remainNum % 10; 21 | // remainNum /= 10; 22 | // int d7 = remainNum % 10; 23 | // remainNum /= 10; 24 | // int d6 = remainNum % 10; 25 | // remainNum /= 10; 26 | // int d5 = remainNum % 10; 27 | // remainNum /= 10; 28 | // int d4 = remainNum % 10; 29 | // remainNum /= 10; 30 | // int d3 = remainNum % 10; 31 | // remainNum /= 10; 32 | // int d2 = remainNum % 10; 33 | // remainNum /= 10; 34 | // int d1 = remainNum % 10; 35 | // 36 | // int d10 = (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11; 37 | 38 | int sum = 0; 39 | for (int i = 9; i >= 1; i--) { 40 | sum += remainNum % 10 * i; 41 | remainNum /= 10; 42 | } 43 | int d10 = sum % 11; 44 | 45 | String ISBN10str = String.format("%09d", originalNum); // Append "0" on the left to make it 9 digits 46 | if (d10 == 10) { 47 | ISBN10str += "X"; 48 | } else { 49 | ISBN10str += d10; 50 | } 51 | 52 | System.out.print("The ISBN-10 number is " + ISBN10str); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0537_Decimal_to_binary.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Decimal to binary) Write a program that prompts the user to enter a decimal 3 | * integer then displays its corresponding binary value. Don’t use Java’s Integer 4 | * .toBinaryString(int) in this program. 5 | * 6 | * Created by Sven on 4/14/2019. 7 | */ 8 | package Chapter05; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0537_Decimal_to_binary { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Enter a number: "); 16 | int originalNum = input.nextInt(); 17 | int decNum = originalNum; 18 | String binStr = ""; 19 | 20 | while (decNum > 0) { 21 | binStr = decNum % 2 + binStr; // Padding the binary string in reverse order 22 | decNum = decNum / 2; 23 | } 24 | System.out.println("Binary representation of " + originalNum + ": " + binStr); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0538_Decimal_to_octal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Decimal to octal) Write a program that prompts the user to enter a decimal 3 | * integer and displays its corresponding octal value. Don’t use Java’s Integer. 4 | * toOctalString(int) in this program. 5 | * 6 | * Created by Sven on 4/14/2019. 7 | */ 8 | package Chapter05; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0538_Decimal_to_octal { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Enter a number: "); 16 | int originalNum = input.nextInt(); 17 | int decNum = originalNum; 18 | String octStr = ""; 19 | 20 | while (decNum > 0) { 21 | octStr = decNum % 8 + octStr; // Padding the octal string in reverse order 22 | decNum = decNum / 8; 23 | } 24 | System.out.println("Binary representation of " + originalNum + ": " + octStr); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0539_Financial_application_find_the_sales_amount.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: find the sales amount) You have just started a sales job in a 3 | * department store. Your pay consists of a base salary and a commission. The base salary 4 | * is $5,000. The scheme shown below is used to determine the commission rate. 5 | * Sales Amount Commission Rate 6 | * $0.01–$5,000 6 percent 7 | * $5,000.01–$10,000 8 percent 8 | * $10,000.01 and above 10 percent 9 | * Note that this is a graduated rate. The rate for the first $5,000 is at 6%, the next 10 | * $5000 is at 8%, and the rest is at 10%. If your sales amounts to $25,000, the commission 11 | * is 5,000 * 6% + 5,000 * 8% + 15,000 * 10% = 2,200. Your goal is to 12 | * earn $30,000 a year. Write a program to find the minimum sales you have to generate 13 | * in order to make $30,000. 14 | * 15 | * Created by Sven on 4/14/2019. 16 | */ 17 | package Chapter05; 18 | 19 | public class Exercise0539_Financial_application_find_the_sales_amount { 20 | public static void main(String[] args) { 21 | double commission; 22 | double salesAmount = 0.0; 23 | do { 24 | salesAmount += 0.01; 25 | 26 | if (salesAmount > 10000.0) { 27 | commission = 700.0 + (salesAmount - 10000.0) * 0.1; 28 | } else if (salesAmount > 5000.0) { 29 | commission = 300.0 + (salesAmount - 5000.0) * 0.08; 30 | } else { 31 | commission = salesAmount * 0.06; 32 | } 33 | } while (salesAmount - commission < 30000.0); 34 | 35 | System.out.println("You need $" + (int) salesAmount + " sales amount to make a commission of $30000"); 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0540_Simulation_heads_or_tails.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Simulation: heads or tails) Write a program that simulates flipping a coin two 3 | * millions times and displays the number of heads and tails. 4 | * 5 | * Created by Sven on 4/14/2019. 6 | */ 7 | package Chapter05; 8 | 9 | public class Exercise0540_Simulation_heads_or_tails { 10 | public static void main(String[] args) { 11 | int headsCounter = 0, tailsCounter = 0; 12 | for (int i = 0; i < 2000000; i++) { 13 | int flip = (int) (Math.random() * 2); 14 | if (flip == 0) { 15 | headsCounter++; 16 | } else { 17 | tailsCounter++; 18 | } 19 | } 20 | System.out.println("Heads: " + headsCounter + " Tails: " + tailsCounter); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0541_Occurrence_of_max_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Occurrence of max numbers) Write a program that reads integers, finds the largest 3 | * of them, and counts its occurrences. Assume the input ends with number 0. Suppose 4 | * you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the 5 | * occurrence count for 5 is 4. 6 | * (Hint: Maintain two variables, max and count. max stores the current max number 7 | * and count stores its occurrences. Initially, assign the first number to max and 1 to 8 | * count. Compare each subsequent number with max. If the number is greater than 9 | * max, assign it to max and reset count to 1. If the number is equal to max, increment 10 | * count by 1.) 11 | * 12 | * Enter numbers: 3 5 2 5 5 5 0 13 | * The largest number is 5 14 | * The occurrence count of the largest number is 4 15 | * 16 | * Created by Sven on 06/05/19. 17 | */ 18 | package Chapter05; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0541_Occurrence_of_max_numbers { 23 | public static void main(String[] args) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter numbers: "); 26 | 27 | int next = input.nextInt(); 28 | int max = next; 29 | int count = 1; 30 | 31 | while (next != 0) { 32 | next = input.nextInt(); 33 | if (next > max) { 34 | max = next; 35 | count = 1; 36 | } else if (next == max) { 37 | count++; 38 | } 39 | } 40 | 41 | System.out.println("The largest number is " + max); 42 | System.out.println("The occurrence count of the largest number is " + count); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0542_Financial_application_find_the_sales_amount.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: find the sales amount) Rewrite Programming Exercise 5.39 3 | * as follows: 4 | * ■ Use a while loop instead of a do-while loop. 5 | * ■ Let the user enter COMMISSION_SOUGHT instead of fixing it as a constant. 6 | * 7 | * Created by Sven on 06/05/19. 8 | */ 9 | package Chapter05; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0542_Financial_application_find_the_sales_amount { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | 17 | double commission = 0.0; 18 | double salesAmount = 0.0; 19 | 20 | System.out.print("Enter commission amount: "); 21 | double COMMISSION_SOUGHT = input.nextInt(); 22 | 23 | while (salesAmount - commission < COMMISSION_SOUGHT) { 24 | salesAmount += 0.01; 25 | 26 | if (salesAmount > 10000.0) { 27 | commission = 700.0 + (salesAmount - 10000.0) * 0.1; 28 | } else if (salesAmount > 5000.0) { 29 | commission = 300.0 + (salesAmount - 5000.0) * 0.08; 30 | } else { 31 | commission = salesAmount * 0.06; 32 | } 33 | } 34 | 35 | System.out.println("You need $" + (int) salesAmount + " sales amount to make a commission of $" + COMMISSION_SOUGHT); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0543_Math_combinations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Math: combinations) Write a program that displays all possible combinations 3 | * for picking two numbers from integers 1 to 7. Also display the total number of 4 | * all combinations. 5 | * 6 | * 1 2 7 | * 1 3 8 | * ... 9 | * ... 10 | * The total number of all combinations is 21 11 | * 12 | * Created by Sven on 06/05/19. 13 | */ 14 | package Chapter05; 15 | 16 | public class Exercise0543_Math_combinations { 17 | public static void main(String[] args) { 18 | int count = 0; 19 | for (int i = 1; i < 8; i++) { 20 | for (int j = i + 1; j < 8; j++) { 21 | System.out.println(i + " " + j); 22 | count++; 23 | } 24 | } 25 | System.out.println("The total number of all combinations is " + count); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0544_Computer_architecture_bit_level_operations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Computer architecture: bit-level operations) A byte value is stored in 8 bits. Write 3 | * a program that prompts the user to enter a byte integer and displays the 8 bits for 4 | * the integer. Here are sample runs: 5 | * 6 | * Enter an integer: 5 7 | * The 8 bits are 00000101 8 | * 9 | * Enter an integer: –5 10 | * The 8 bits are 11111011 11 | * 12 | * (Hint: You need to use the bitwise right shift operator (>>) and the bitwise AND 13 | * operator (&), which are covered in Appendix G, Bitwise Operations.) 14 | * 15 | * Created by Sven on 06/05/19. 16 | */ 17 | package Chapter05; 18 | 19 | import java.util.Scanner; 20 | 21 | public class Exercise0544_Computer_architecture_bit_level_operations { 22 | public static void main(String[] args) { 23 | Scanner input = new Scanner(System.in); 24 | System.out.print("Enter an integer: "); 25 | int number = input.nextInt(); 26 | 27 | System.out.print("he 8 bits are "); 28 | for (int i = 7; i >= 0; i--) { 29 | System.out.print((number >> i) & 1); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0545_Statistics_compute_mean_and_standard_deviation.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Statistics: compute mean and standard deviation) In business applications, you 3 | * are often asked to compute the mean and standard deviation of data. The mean is 4 | * simply the average of the numbers. The standard deviation is a statistic that tells 5 | * you how tightly all the various data are clustered around the mean in a set of data. 6 | * For example, what is the average age of the students in a class? How close are the 7 | * ages? If all the students are the same age, the deviation is 0. 8 | * Write a program that prompts the user to enter 10 numbers and displays the mean 9 | * and standard deviations of these numbers using the following formula: 10 | * 11 | * Here is a sample run: 12 | * Enter 10 numbers: 1 2 3 4.5 5.6 6 7 8 9 10 13 | * The mean is 5.61 14 | * The standard deviation is 2.99794 15 | * 16 | * Created by Sven on 06/05/19. 17 | */ 18 | package Chapter05; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0545_Statistics_compute_mean_and_standard_deviation { 23 | public static void main(String[] args) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter 10 numbers: "); 26 | 27 | double sum = 0.0; 28 | double square_sum = 0.0; 29 | int count = 0; 30 | 31 | for (int i = 0; i < 10; i++) { 32 | double next = input.nextDouble(); 33 | sum += next; 34 | square_sum += Math.pow(next, 2); 35 | count++; 36 | } 37 | 38 | System.out.println("The mean is " + sum / count); 39 | System.out.println("The standard deviation is " + Math.sqrt((square_sum - (Math.pow(sum, 2) / count)) / (count - 1))); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0546_Reverse_a_string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Reverse a string) Write a program that prompts the user to enter a string and 3 | * displays the string in reverse order. 4 | * 5 | * Enter a string: ABCD 6 | * The reversed string is DCBA 7 | * 8 | * Created by Sven on 06/05/19. 9 | */ 10 | package Chapter05; 11 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise0546_Reverse_a_string { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter a string: "); 18 | 19 | String str = input.next(); 20 | String reverse_str = ""; 21 | 22 | for (int i = str.length() - 1; i >= 0; i--) { 23 | reverse_str += str.charAt(i); 24 | } 25 | System.out.print("The reversed string is " + reverse_str); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0547_Business_check_ISBN_13.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Business: check ISBN-13) ISBN-13 is a new standard for identifying books. It uses 3 | * 13 digits d1d2d3d4d5d6d7d8d9d10d11d12d13. The last digit d13 is a checksum, which is 4 | * calculated from the other digits using the following formula: 5 | * 10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12),10 6 | * If the checksum is 10, replace it with 0. Your program should read the input as a 7 | * string. Here are sample runs: 8 | * 9 | * Enter the first 12 digits of an ISBN-13 as a string: 978013213080 10 | * The ISBN-13 number is 9780132130806 11 | * Enter the first 12 digits of an ISBN-13 as a string: 978013213079 12 | * The ISBN-13 number is 9780132130790 13 | * Enter the first 12 digits of an ISBN-13 as a string: 97801320 14 | * 97801320 is an invalid input 15 | * 16 | * Created by Sven on 06/09/19. 17 | */ 18 | package Chapter05; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0547_Business_check_ISBN_13 { 23 | public static void main(String[] args) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter the first 12 digits of an ISBN as integer: "); 26 | String originalNum = input.next(); 27 | 28 | if (originalNum.length() != 12) { 29 | System.out.println(originalNum + " is an invalid input"); 30 | } else { 31 | int sum = 0; 32 | for (int i = 0; i < originalNum.length(); i++) { 33 | sum += (i % 2 == 0) ? 3 * (originalNum.charAt(i) - 48) : (originalNum.charAt(i) - 48); 34 | } 35 | int checksum = (10 - sum % 10) % 10; // If the checksum is 10, replace it with 0, therefore % 10 36 | 37 | String ISBN13str = originalNum + checksum; 38 | 39 | System.out.print("The ISBN-13 number is " + ISBN13str); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0548_Process_string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Process string) Write a program that prompts the user to enter a string and displays 3 | * the characters at even positions. Here is a sample run: 4 | * 5 | * Enter a string: Beijing Chicago 6 | * ejnhcg 7 | * 8 | * Created by Sven on 06/10/19. 9 | */ 10 | package Chapter05; 11 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise0548_Process_string { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter a string: "); 18 | String str = input.nextLine(); 19 | for (int i = 1; i < str.length(); i += 2) { 20 | System.out.print(str.charAt(i)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0549_Count_vowels_and_consonants.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Count vowels and consonants) Assume that the letters A, E, I, O, and U are vowels. 3 | * Write a program that prompts the user to enter a string, and displays the number of 4 | * vowels and consonants in the string. 5 | * 6 | * Enter a string: Programming is fun 7 | * The number of vowels is 5 8 | * The number of consonants is 11 9 | * 10 | * Created by Sven on 06/10/19. 11 | */ 12 | package Chapter05; 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise0549_Count_vowels_and_consonants { 17 | public static void main(String[] args) { 18 | Scanner input = new Scanner(System.in); 19 | System.out.print("Enter a string: "); 20 | String str = input.nextLine(); 21 | 22 | int numOfVow = 0, numOfCon = 0; 23 | 24 | for (int i = 0; i < str.length(); i++) { 25 | char ch = str.charAt(i); 26 | 27 | if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' || 28 | ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { 29 | numOfVow++; 30 | } else if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { 31 | numOfCon++; 32 | } 33 | } 34 | System.out.println("The number of vowels is " + numOfVow); 35 | System.out.println("The number of consonants is " + numOfCon); 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/Chapter05/Exercise0551_Longest_common_prefix.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Longest common prefix) Write a program that prompts the user to enter two 3 | * strings and displays the largest common prefix of the two strings. Here are some 4 | * sample runs: 5 | * 6 | * Enter the first string: Welcome to C++ 7 | * Enter the second string: Welcome to programming 8 | * The common prefix is Welcome to 9 | * 10 | * Enter the first string: Atlanta 11 | * Enter the second string: Macon 12 | * Atlanta and Macon have no common prefix 13 | * 14 | * Created by Sven on 06/10/19. 15 | */ 16 | package Chapter05; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0551_Longest_common_prefix { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | 24 | System.out.print("Enter the first string: "); 25 | String firstStr = input.nextLine(); 26 | 27 | System.out.print("Enter the second string: "); 28 | String secondStr = input.nextLine(); 29 | 30 | String commonPrefix = ""; 31 | 32 | int minLen = (firstStr.length() <= secondStr.length()) ? firstStr.length() : secondStr.length(); 33 | for (int i = 0; i < minLen; i++) { 34 | if (firstStr.charAt(i) == secondStr.charAt(i)) { 35 | commonPrefix += firstStr.charAt(i); 36 | } else { 37 | break; 38 | } 39 | } 40 | 41 | if (commonPrefix.length() == 0) { 42 | System.out.println(firstStr + " and " + secondStr + " have no common prefix"); 43 | } else { 44 | System.out.println("The common prefix is " + commonPrefix); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0601_Math_pentagonal_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Math: pentagonal numbers) A pentagonal number is defined as n(3n-1)/2 for 3 | * n = 1 , 2 , …, and so on. Therefore, the first few numbers are 1, 5, 12, 22, 4 | * . . . . Write a method with the following header that returns a pentagonal 5 | * number: 6 | * public static int getPentagonalNumber(int n) 7 | * For example, getPentagonalNumber(1) returns 1 and getPentagonalNumber( 8 | * 2) returns 5. Write a test program that uses this method to display the 9 | * first 100 pentagonal numbers with 10 numbers on each line. Use the %7d format 10 | * to display each number. 11 | * 12 | * Created by Sven on 06/16/19. 13 | */ 14 | package Chapter06; 15 | 16 | public class Exercise0601_Math_pentagonal_numbers { 17 | public static void main(String[] args) { 18 | for (int i = 1; i <= 100; i++) { 19 | System.out.printf("%6d", getPentagonalNumber(i)); 20 | if (i % 10 == 0) { 21 | System.out.println(); 22 | } 23 | } 24 | } 25 | 26 | public static int getPentagonalNumber(int n) { 27 | return n * (3 * n - 1) / 2; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0602_Sum_the_digits_in_an_integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sum the digits in an integer) Write a method that computes the sum of the digits 3 | * in an integer. Use the following method header: 4 | * public static int sumDigits(long n) 5 | * For example, sumDigits(234) returns 9 (= 2 + 3 + 4). (Hint: Use the % operator 6 | * to extract digits and the / operator to remove the extracted digit. For instance, 7 | * to extract 4 from 234, use 234 % 10 (= 4 ). To remove 4 from 234, use 234 / 10 8 | * (= 2 3 ). Use a loop to repeatedly extract and remove the digit until all the digits 9 | * are extracted. Write a test program that prompts the user to enter an integer then 10 | * displays the sum of all its digits. 11 | * 12 | * Created by Sven on 06/16/19. 13 | */ 14 | package Chapter06; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0602_Sum_the_digits_in_an_integer { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter a integer: "); 22 | int integer = input.nextInt(); 23 | 24 | System.out.println("The sum of the digits in " + integer + " is " + sumDigits(integer)); 25 | } 26 | 27 | public static int sumDigits(long n) { 28 | int sum = 0; 29 | while (n != 0) { 30 | sum += n % 10; 31 | n /= 10; 32 | } 33 | return sum; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0603_Palindrome_integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Palindrome integer) Write the methods with the following headers: 3 | * // Return the reversal of an integer, e.g., reverse(456) returns 654 4 | * public static int reverse(int number) 5 | * // Return true if number is a palindrome 6 | * public static boolean isPalindrome(int number) 7 | * Use the reverse method to implement isPalindrome. A number is a palindrome 8 | * if its reversal is the same as itself. Write a test program that prompts the 9 | * user to enter an integer and reports whether the integer is a palindrome. 10 | * 11 | * Created by Sven on 06/16/19. 12 | */ 13 | package Chapter06; 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise0603_Palindrome_integer { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | System.out.print("Enter a number:"); 21 | int number = input.nextInt(); 22 | System.out.println(isPalindrome(number) ? (number + " is a palindrome integer") : (number + " is not a palindrome integer")); 23 | } 24 | 25 | public static int reverse(int number) { 26 | int reverse = 0; 27 | while (number != 0) { 28 | reverse *= 10; 29 | reverse += number % 10; 30 | number /= 10; 31 | } 32 | return reverse; 33 | } 34 | 35 | public static boolean isPalindrome(int number) { 36 | return number == reverse(number); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0604_Display_an_integer_reversed.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display an integer reversed) Write a method with the following header to display 3 | * an integer in reverse order: 4 | * public static void reverse(int number) 5 | * For example, reverse(3456) displays 6543. Write a test program that prompts 6 | * the user to enter an integer then displays its reversal. 7 | * 8 | * Created by Sven on 06/16/19. 9 | */ 10 | package Chapter06; 11 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise0604_Display_an_integer_reversed { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter a number:"); 18 | int number = input.nextInt(); 19 | reverse(number); 20 | } 21 | 22 | public static void reverse(int number) { 23 | int reverse = 0; 24 | while (number != 0) { 25 | reverse *= 10; 26 | reverse += number % 10; 27 | number /= 10; 28 | } 29 | System.out.println(reverse); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0605_Sort_three_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sort three numbers) Write a method with the following header to display three 3 | * numbers in decreasing order: 4 | * public static void displaySortedNumbers( 5 | * double num1, double num2, double num3) 6 | * Write a test program that prompts the user to enter three numbers and invokes the 7 | * method to display them in decreasing order. 8 | * 9 | * Created by Sven on 06/16/19. 10 | */ 11 | package Chapter06; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0605_Sort_three_numbers { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter 3 numbers: "); 19 | double num1 = input.nextDouble(); 20 | double num2 = input.nextDouble(); 21 | double num3 = input.nextDouble(); 22 | 23 | displaySortedNumbers(num1, num2, num3); 24 | } 25 | 26 | public static void displaySortedNumbers(double num1, double num2, double num3) { 27 | double temp = 0; 28 | if (num1 < num2) { 29 | temp = num1; 30 | num1 = num2; 31 | num2 = temp; 32 | } 33 | if (num2 < num3) { 34 | temp = num2; 35 | num2 = num3; 36 | num3 = temp; 37 | } 38 | if (num1 < num2) { 39 | temp = num1; 40 | num1 = num2; 41 | num2 = temp; 42 | } 43 | System.out.println(num1 + " " + num2 + " " + num3); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0606_Display_patterns.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display patterns) Write a method to display a pattern as follows: 3 | * 1 4 | * 1 2 5 | * 1 2 3 6 | * ... 7 | * 1 2 3 ... n-1 n 8 | * The method header is 9 | * public static void displayPattern(int n) 10 | * 11 | * Created by Sven on 06/16/19. 12 | */ 13 | package Chapter06; 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise0606_Display_patterns { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | System.out.print("Enter a number:"); 21 | int number = input.nextInt(); 22 | displayPattern(number); 23 | } 24 | 25 | public static void displayPattern(int n) { 26 | for (int i = 1; i <= n; i++) { 27 | for (int j = 1; j <= i; j++) { 28 | System.out.printf(j + " "); 29 | } 30 | System.out.println(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0608_Conversions_between_mile_and_kilometer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Conversions between mile and kilometer) Write a class that contains the following 3 | * two methods: 4 | * public static double mileToKilometer(double mile) 5 | * public static double kilometerToMile(double kilometer) 6 | * 7 | * The formula for the conversion is: 8 | * 1 mile = 1.6 kilometers 9 | * Write a test program that invokes these methods to display the following tables: 10 | * Miles Kilometers | Kilometers Miles 11 | * 1 1.609 | 20 12.430 12 | * 2 3.218 | 25 15.538 13 | * ... 14 | * 9 14.481 | 60 37.290 15 | * 10 16.090 | 65 40.398 16 | * 17 | * Created by Sven on 06/16/19. 18 | */ 19 | package Chapter06; 20 | 21 | public class Exercise0608_Conversions_between_mile_and_kilometer { 22 | public static void main(String[] args) { 23 | System.out.printf("%-15s%-15s%-5s%-15s%-15s\n", "Miles", "Kilometers", "|", "Kilometers", "Miles"); 24 | System.out.println("--------------------------------------------------------"); 25 | for (int i = 1; i <= 10; i++) { 26 | System.out.printf("%-15d%-15.3f%-5s%-15d%-15.3f\n", i, mileToKilometer(i), "|", 15 + 5 * i, kilometerToMile(15 + 5 * i)); 27 | } 28 | } 29 | 30 | /** 31 | * Convert from Mile to Kilometer 32 | */ 33 | public static double mileToKilometer(double mile) { 34 | return mile * 1.6; 35 | } 36 | 37 | /** 38 | * Convert from Kilometer to Mile 39 | */ 40 | public static double kilometerToMile(double kilometer) { 41 | return kilometer / 1.6; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0609_Conversions_between_pounds_and_kilograms.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Conversions between pounds and kilograms) Write a class that contains the 3 | * following two methods: 4 | * public static double poundToKilogram(double pound) 5 | * public static double kilogramToPound(double kilogram) 6 | * The formula for the conversion is: 7 | * pound=0.453*kilogram 8 | * kilogram=2.204*pound 9 | * Write a test program that invokes these methods to display the following tables: 10 | * Kilograms Pounds|Pounds Kilograms 11 | * 1 2.2|20 9.09 12 | * 3 6.6|25 11.36 13 | * ... 14 | * 197 433.4|510 231.82 15 | * 199 437.8|515 234.09 16 | * 17 | * Created by Sven on 06/16/19. 18 | */ 19 | package Chapter06; 20 | 21 | public class Exercise0609_Conversions_between_pounds_and_kilograms { 22 | public static void main(String[] args) { 23 | System.out.printf("%-15s%-15s%-5s%-15s%-15s\n", "Kilograms", "Pounds", "|", "Pounds", "Kilograms"); 24 | System.out.println("-----------------------------------------------------------"); 25 | for (int i = 0; i <= 99; i++) { 26 | System.out.printf("%-15d%-15.1f%-5s%-15d%-15.2f\n", 1 + i * 2, kilogramToPound(1 + i * 2), "|", 20 + 5 * i, poundToKilogram(20 + 5 * i)); 27 | } 28 | } 29 | 30 | /** 31 | * Convert from pounds to kilograms 32 | */ 33 | public static double poundToKilogram(double pound) { 34 | return 0.453 * pound; 35 | } 36 | 37 | /** 38 | * Convert from kilograms to pounds 39 | */ 40 | public static double kilogramToPound(double kilogram) { 41 | return 2.204 * kilogram; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0610_Use_the_isPrime_Method.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Use the isPrime Method) Listing 6.7, PrimeNumberMethod.java, provides the 3 | * isPrime(int number) method for testing whether a number is prime. Use this 4 | * method to find the number of prime numbers less than 10000. 5 | * 6 | * Created by Sven on 06/16/19. 7 | */ 8 | package Chapter06; 9 | 10 | public class Exercise0610_Use_the_isPrime_Method { 11 | public static void main(String[] args) { 12 | int count = 0; 13 | for (int i = 2; i < 10001; i++) { 14 | if (isPrime(i)) { 15 | count++; 16 | } 17 | } 18 | System.out.println("Total number of prime numbers from 1-10000 is " + count); 19 | } 20 | 21 | /** 22 | * Check whether number is prime 23 | */ 24 | public static boolean isPrime(int number) { 25 | for (int divisor = 2; divisor <= number / 2; divisor++) { 26 | if (number % divisor == 0) { // If true, number is not prime 27 | return false; // number is not a prime 28 | } 29 | } 30 | return true; // number is prime 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0611_Financial_application_compute_commissions.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Financial application: compute commissions) Write a method that computes the 3 | * commission, using the scheme in Programming Exercise 5.39. The header of 4 | * the method is as follows: 5 | * public static double computeCommission(double salesAmount) 6 | * Write a test program that displays the following table: 7 | * Sales Amount Commission 8 | * 10000 900.0 9 | * 15000 1500.0 10 | * ... 11 | * 95000 11100.0 12 | * 100000 11700.0 13 | * 14 | * Created by Sven on 07/07/19. 15 | */ 16 | package Chapter06; 17 | 18 | public class Exercise0611_Financial_application_compute_commissions { 19 | public static void main(String[] args) { 20 | System.out.println("Sales Amount Commission"); 21 | System.out.println("--------------------------"); 22 | for (int i = 10000; i <= 100000; i += 5000) { 23 | System.out.printf("%-16d%10.1f\n", i, computeCommission(i)); 24 | } 25 | } 26 | 27 | public static double computeCommission(double salesAmount) { 28 | double commission = 0.0; 29 | if (salesAmount > 10000.0) { 30 | commission = 700.0 + (salesAmount - 10000.0) * 0.1; 31 | } else if (salesAmount > 5000.0) { 32 | commission = 300.0 + (salesAmount - 5000.0) * 0.08; 33 | } else { 34 | commission = salesAmount * 0.06; 35 | } 36 | return commission; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0612_Display_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display numbers) Write a method that prints numbers using the following header: 3 | * public static void printNumbers(int num1, int num2, int 4 | * numberPerLine) 5 | * This method prints the characters between num1 and num2 with the specified 6 | * numbers per line. Write a test program that prints ten characters per line from 1 7 | * to 100. Numbers are separated by exactly one space. 8 | * 9 | * Created by Sven on 07/07/19. 10 | */ 11 | package Chapter06; 12 | 13 | public class Exercise0612_Display_numbers { 14 | public static void main(String[] args) { 15 | printNumbers(1, 100, 10); 16 | } 17 | 18 | public static void printNumbers(int num1, int num2, int numberPerLine) { 19 | int count = 0; 20 | for (int i = num1; i <= num2; i++) { 21 | System.out.print(i + " "); 22 | count++; 23 | if (count % numberPerLine == 0) { 24 | System.out.println(); 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0613_Sum_series.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sum series) Write a method to compute the following series: 3 | * m(i) = 1/3 +2/4 + ... + i/i+2 4 | * Write a test program that displays the following table: 5 | * I m(i) 6 | * 1 0.3333 7 | * 2 0.8333 8 | * ... 9 | * 19 14.7093 10 | * 20 15.6184 11 | * 12 | * Created by Sven on 07/07/19. 13 | */ 14 | package Chapter06; 15 | 16 | public class Exercise0613_Sum_series { 17 | public static void main(String[] args) { 18 | System.out.println("i m(i)"); 19 | System.out.println("---------"); 20 | for (int i = 1; i <= 20; i++) { 21 | System.out.printf("%-5d%.4f\n", i, computeSum(i)); 22 | } 23 | } 24 | 25 | public static double computeSum(int i) { 26 | double sum = 0.0; 27 | for (int j = 1; j <= i; j++) { 28 | sum += (double) j / (double) (j + 2); 29 | } 30 | return sum; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0614_Estimate_PI.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Estimate p) p can be computed using the following summation: 3 | * m (i) = 4 (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... + ((-1)^(i+1))/(2i-1)) 4 | * Write a method that returns m(i) for a given i and write a test program that 5 | * displays the following table: 6 | * i m(i) 7 | * 1 4.0000 8 | * 101 3.1515 9 | * 201 3.1466 10 | * 301 3.1449 11 | * 401 3.1441 12 | * 501 3.1436 13 | * 601 3.1433 14 | * 701 3.1430 15 | * 801 3.1428 16 | * 901 3.1427 17 | * 18 | * Created by Sven on 07/07/19. 19 | */ 20 | package Chapter06; 21 | 22 | public class Exercise0614_Estimate_PI { 23 | public static void main(String[] args) { 24 | System.out.println("i m(i)"); 25 | System.out.println("---------"); 26 | for (int i = 1; i <= 901; i += 100) { 27 | System.out.printf("%-5d%.4f\n", i, computePI(i)); 28 | } 29 | } 30 | 31 | public static double computePI(int i) { 32 | double sum = 0.0; 33 | for (int j = 1; j <= i; j++) { 34 | sum += 4 * (Math.pow(-1, j + 1) / (2 * j - 1)); 35 | } 36 | return sum; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0616_Number_of_days_in_a_year.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Number of days in a year) Write a method that returns the number of days in a 3 | * year using the following header: 4 | * public static int numberOfDaysInAYear(int year) 5 | * Write a test program that displays the number of days in the years between 2014 6 | * and 2034. 7 | * 8 | * Created by Sven on 07/16/19. 9 | */ 10 | package Chapter06; 11 | 12 | public class Exercise0616_Number_of_days_in_a_year { 13 | public static void main(String[] args) { 14 | System.out.println("Year Num of Days"); 15 | System.out.println("-------------------"); 16 | for (int i = 2014; i <= 2034; i++) { 17 | System.out.println(i + " " + numberOfDaysInAYear(i)); 18 | } 19 | } 20 | 21 | public static int numberOfDaysInAYear(int year) { 22 | return isLeapYear(year) ? 366 : 365; 23 | } 24 | 25 | public static boolean isLeapYear(int year) { 26 | if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { 27 | return true; 28 | } 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0617_Display_matrix_of_0s_and_1s.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Display matrix of 0s and 1s) Write a method that displays an n-by-n matrix using 3 | * the following header: 4 | * public static void printMatrix(int n) 5 | * Each element is 0 or 1, which is generated randomly. Write a test program 6 | * that prompts the user to enter n and displays an n-by-n matrix. Here is a 7 | * sample run: 8 | * Enter n: 3 9 | * 0 1 0 10 | * 0 0 0 11 | * 1 1 1 12 | * 13 | * Created by Sven on 07/16/19. 14 | */ 15 | package Chapter06; 16 | 17 | import java.util.Scanner; 18 | 19 | public class Exercise0617_Display_matrix_of_0s_and_1s { 20 | public static void main(String[] args) { 21 | Scanner input = new Scanner(System.in); 22 | System.out.print("Enter n: "); 23 | int n = input.nextInt(); 24 | printMatrix(n); 25 | } 26 | 27 | public static void printMatrix(int n) { 28 | for (int i = 0; i < n; i++) { 29 | for (int j = 0; j < n; j++) { 30 | System.out.print(Math.random() < 0.5 ? 0 + " " : 1 + " "); 31 | } 32 | System.out.println(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0620_Count_the_letters_in_a_string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Count the letters in a string) Write a method that counts the number of letters in 3 | * a string using the following header: 4 | * public static int countLetters(String s) 5 | * Write a test program that prompts the user to enter a string and displays the number 6 | * of letters in the string. 7 | * 8 | * Created by Sven on 07/16/19. 9 | */ 10 | package Chapter06; 11 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise0620_Count_the_letters_in_a_string { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter a string: "); 18 | String str = input.nextLine(); 19 | System.out.println("The number of letters: " + countLetters(str)); 20 | } 21 | 22 | public static int countLetters(String s) { 23 | int letterCount = 0; 24 | for (int i = 0; i < s.length(); i++) { 25 | char ch = s.charAt(i); 26 | if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { 27 | letterCount++; 28 | } 29 | } 30 | return letterCount; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0622_Math_approximate_the_square_root.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Math: approximate the square root) There are several techniques for implementing 3 | * the sqrt method in the Math class. One such technique is known as the 4 | * Babylonian method. It approximates the square root of a number, n, by repeatedly 5 | * performing the calculation using the following formula: 6 | * nextGuess = (lastGuess + n / lastGuess) / 2 7 | * When nextGuess and lastGuess are almost identical, nextGuess is the 8 | * approximated square root. The initial guess can be any positive value (e.g., 1). 9 | * This value will be the starting value for lastGuess. If the difference between 10 | * nextGuess and lastGuess is less than a very small number, such as 0.0001, 11 | * you can claim that nextGuess is the approximated square root of n. If not, nextGuess 12 | * becomes lastGuess and the approximation process continues. Implement 13 | * the following method that returns the square root of n: 14 | * public static double sqrt(long n) 15 | * 16 | * Created by Sven on 07/16/19. 17 | */ 18 | package Chapter06; 19 | 20 | import java.util.Scanner; 21 | 22 | public class Exercise0622_Math_approximate_the_square_root { 23 | public static void main(String[] args) { 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter a number: "); 26 | long number = input.nextLong(); 27 | System.out.println("Approximate the square root: " + sqrt(number)); 28 | } 29 | 30 | public static double sqrt(long n) { 31 | double accuracy = 0.0001; 32 | double lastGuess = 1; 33 | double nextGuess = 1; 34 | do { 35 | lastGuess = nextGuess; 36 | nextGuess = (lastGuess + n / lastGuess) / 2; 37 | } while (Math.abs(nextGuess - lastGuess) > accuracy); 38 | return nextGuess; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0623_Occurrences_of_a_specified_character.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Occurrences of a specified character) Write a method that finds the number of 3 | * occurrences of a specified character in a string using the following header: 4 | * public static int count(String str, char a) 5 | * 6 | * Created by Sven on 07/16/19. 7 | */ 8 | package Chapter06; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0623_Occurrences_of_a_specified_character { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Enter a string: "); 16 | String str = input.nextLine(); 17 | System.out.print("Enter a character: "); 18 | char ch = input.next().charAt(0); 19 | 20 | System.out.println("The number of occurrences of " + ch + " in " + str + " is " + count(str, ch)); 21 | } 22 | 23 | public static int count(String str, char a) { 24 | int count = 0; 25 | for (int i = 0; i < str.length(); i++) { 26 | if (str.charAt(i) == a) { 27 | count++; 28 | } 29 | } 30 | return count; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0625_Convert_milliseconds_to_hours_minutes_and_seconds.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Convert milliseconds to hours, minutes, and seconds) Write a method that converts 3 | * milliseconds to hours, minutes, and seconds using the following header: 4 | * public static String convertMillis(long millis) 5 | * The method returns a string as hours:minutes:seconds. For example, 6 | * convertMillis(5500) returns a string 0:0:5, convertMillis(100000) 7 | * returns a string 0:1:40, and convertMillis(555550000) returns a string 8 | * 154:19:10. Write a test program that prompts the user to enter a long integer for 9 | * milliseconds and displays a string in the format of hours:minutes:seconds. 10 | * 11 | * Created by Sven on 07/23/19. 12 | */ 13 | package Chapter06; 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise0625_Convert_milliseconds_to_hours_minutes_and_seconds { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | System.out.print("Enter the number of milliseconds: "); 21 | long millis = input.nextLong(); 22 | System.out.println(convertMillis(millis)); 23 | } 24 | 25 | public static String convertMillis(long millis) { 26 | long hours = 0; 27 | long minutes = 0; 28 | long seconds = 0; 29 | 30 | long millisInHour = 60 * 60 * 1000; 31 | long millisInMinute = 60 * 1000; 32 | long millisInSecond = 1000; 33 | 34 | hours = millis / millisInHour; 35 | minutes = millis % millisInHour / millisInMinute; 36 | seconds = millis % millisInMinute / millisInSecond; 37 | 38 | return hours + ":" + minutes + ":" + seconds; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0626_Palindromic_prime.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Palindromic prime) A palindromic prime is a prime number and also palindromic. 3 | * For example, 131 is a prime and also a palindromic prime, as are 313 and 757. 4 | * Write a program that displays the first 120 palindromic prime numbers. Display 5 | * 10 numbers per line, separated by exactly one space, as follows: 6 | * 2 3 5 7 11 101 131 151 181 191 7 | * 313 353 373 383 727 757 787 797 919 929 8 | * 9 | * Created by Sven on 07/27/19. 10 | */ 11 | package Chapter06; 12 | 13 | public class Exercise0626_Palindromic_prime { 14 | public static void main(String[] args) { 15 | int count = 0; 16 | for (int i = 0; count < 120; i++) { 17 | // It's slow to compute the last five numbers 18 | if (isPrime(i) && isPalindrome(i)) { 19 | if (count != 0 && count % 10 == 0) { 20 | System.out.println(); 21 | } 22 | System.out.print(i + " "); 23 | count++; 24 | } 25 | } 26 | } 27 | 28 | /** 29 | * Check whether number is prime 30 | */ 31 | public static boolean isPrime(int number) { 32 | for (int divisor = 2; divisor <= number / 2; divisor++) { 33 | if (number % divisor == 0) { // If true, number is not prime 34 | return false; // number is not a prime 35 | } 36 | } 37 | return true; // number is prime 38 | } 39 | 40 | /** 41 | * Check whether number is palindromic 42 | */ 43 | public static int reverse(int number) { 44 | int reverse = 0; 45 | while (number != 0) { 46 | reverse *= 10; 47 | reverse += number % 10; 48 | number /= 10; 49 | } 50 | return reverse; 51 | } 52 | 53 | public static boolean isPalindrome(int number) { 54 | return number == reverse(number); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0627_Emirp.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Emirp) An emirp (prime spelled backward) is a nonpalindromic prime number 3 | * whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 4 | * 17 and 71 are emirps. Write a program that displays the first 120 emirps. Display 5 | * 10 numbers per line, separated by exactly one space, as follows: 6 | * 13 17 31 37 71 73 79 97 107 113 7 | * 149 157 167 179 199 311 337 347 359 389 8 | * 9 | * Created by Sven on 07/27/19. 10 | */ 11 | package Chapter06; 12 | 13 | public class Exercise0627_Emirp { 14 | public static void main(String[] args) { 15 | int count = 0; 16 | for (int i = 2; count < 120; i++) { 17 | // It's slow to compute the last five numbers 18 | if (isPrime(i) && isPrime(reverse(i))) { 19 | if (count != 0 && count % 10 == 0) { 20 | System.out.println(); 21 | } 22 | System.out.print(i + " "); 23 | count++; 24 | } 25 | } 26 | } 27 | 28 | public static boolean isPrime(int number) { 29 | for (int divisor = 2; divisor <= number / 2; divisor++) { 30 | if (number % divisor == 0) { // If true, number is not prime 31 | return false; // number is not a prime 32 | } 33 | } 34 | return true; // number is prime 35 | } 36 | 37 | public static int reverse(int number) { 38 | int reverse = 0; 39 | while (number != 0) { 40 | reverse *= 10; 41 | reverse += number % 10; 42 | number /= 10; 43 | } 44 | return reverse; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0628_Mersenne_prime.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Mersenne prime) A prime number is called a Mersenne prime if it can be written 3 | * in the form 2 p - 1 for some positive integer p. Write a program that finds all 4 | * Mersenne primes with p … 31 and displays the output as follows: 5 | * p 2^p – 1 6 | * 2 3 7 | * 3 7 8 | * 5 31 9 | * ... 10 | * 11 | * Created by Sven on 07/27/19. 12 | */ 13 | package Chapter06; 14 | 15 | public class Exercise0628_Mersenne_prime { 16 | public static void main(String[] args) { 17 | System.out.println("p 2^p - 1"); 18 | System.out.println("----------------"); 19 | for (int p = 2; p <= 31; p++) { 20 | if (isPrime((int) Math.pow(2, p) - 1)) { 21 | System.out.printf("%-9d%d\n", p, (int) Math.pow(2, p) - 1); 22 | } 23 | } 24 | } 25 | 26 | public static boolean isPrime(int number) { 27 | for (int divisor = 2; divisor <= number / 2; divisor++) { 28 | if (number % divisor == 0) { // If true, number is not prime 29 | return false; // number is not a prime 30 | } 31 | } 32 | return true; // number is prime 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0629_Twin_primes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Twin primes) Twin primes are a pair of prime numbers that differ by 2. For 3 | * example, 3 and 5 are twin primes, 5 and 7 are twin primes, and 11 and 13 are 4 | * twin primes. Write a program to find all twin primes less than 1,200. Display the 5 | * output as follows: 6 | * (3, 5) 7 | * (5, 7) 8 | * ... 9 | * 10 | * Created by Sven on 07/27/19. 11 | */ 12 | package Chapter06; 13 | 14 | public class Exercise0629_Twin_primes { 15 | public static void main(String[] args) { 16 | for (int i = 2; i < 1200; i++) { 17 | if (isPrime(i) && isPrime(i + 2)) { 18 | System.out.println("(" + i + ", " + (i + 2) + ")"); 19 | } 20 | } 21 | } 22 | 23 | public static boolean isPrime(int number) { 24 | for (int divisor = 2; divisor <= number / 2; divisor++) { 25 | if (number % divisor == 0) { // If true, number is not prime 26 | return false; // number is not a prime 27 | } 28 | } 29 | return true; // number is prime 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0632_Game_chance_of_winning_at_craps.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: chance of winning at craps) Revise Exercise 6.30 to run it 15,000 times 3 | * and display the number of winning games. 4 | * 5 | * Created by Sven on 07/27/19. 6 | */ 7 | package Chapter06; 8 | 9 | public class Exercise0632_Game_chance_of_winning_at_craps { 10 | public static void main(String[] args) { 11 | int winCount = 0; 12 | int numOfTrail = 15000; 13 | for (int i = 0; i < 15000; i++) { 14 | int point = rollDice(); 15 | if (getStatus(point)) { 16 | System.out.println("You win"); 17 | winCount++; 18 | } else { 19 | System.out.println("You lose"); 20 | } 21 | } 22 | 23 | System.out.println("\nYou won " + winCount + " times in " + numOfTrail + " trails"); 24 | 25 | } 26 | 27 | public static boolean getStatus(int point) { 28 | if (point == 7 || point == 11) { 29 | return true; 30 | } else if (point == 2 || point == 3 || point == 12) { 31 | return false; 32 | } else { 33 | System.out.println("point is " + point); 34 | int secondPoint = rollDice(); 35 | while (true) { 36 | if (secondPoint == point) { 37 | return true; 38 | } else if (secondPoint == 7) { 39 | return false; 40 | } else { 41 | System.out.println("point is " + secondPoint); 42 | secondPoint = rollDice(); 43 | } 44 | } 45 | } 46 | } 47 | 48 | 49 | public static int rollDice() { 50 | int dice1 = (int) (Math.random() * 6 + 1); 51 | int dice2 = (int) (Math.random() * 6 + 1); 52 | int point = dice1 + dice2; 53 | System.out.println("You rolled " + dice1 + " + " + dice2 + " = " + point); 54 | return point; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0633_Current_date_and_time.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Current date and time) Invoking System.currentTimeMillis() returns the 3 | * elapsed time in milliseconds since midnight of January 1, 1970. Write a program 4 | * that displays the date and time. Here is a sample run: 5 | * Current date and time is May 16, 2012 10:34:23 6 | * 7 | * Created by Sven on 07/27/19. 8 | */ 9 | package Chapter06; 10 | 11 | 12 | import static Chapter06.Exercise0624_Display_current_date_and_time.*; 13 | 14 | public class Exercise0633_Current_date_and_time { 15 | // Same as Exercise0624 16 | public static void main(String[] args) { 17 | long totalMilliseconds = System.currentTimeMillis(); 18 | long totalSeconds = totalMilliseconds / 1000; 19 | long currentSecond = totalSeconds % 60; 20 | long totalMinutes = totalSeconds / 60; 21 | long currentMinute = totalMinutes % 60; 22 | long totalHours = totalMinutes / 60; 23 | long currentHour = totalHours % 24; 24 | long totalDays = totalHours / 24 + 1; 25 | int currentYear = getCurrentYear(totalDays); 26 | int daysInCurrentYear = getDaysInCurrentYear(currentYear, totalDays); 27 | int currentMonth = getCurrentMonth(currentYear, daysInCurrentYear); 28 | int currentDay = getCurrentDay(currentYear, currentMonth, daysInCurrentYear); 29 | int currentDayOfTheWeek = (getStartDay(currentYear, currentMonth) + currentDay) % 7; 30 | System.out.println("Current date and time is " 31 | + getDayName(currentDayOfTheWeek) + " " 32 | + getMonthName(currentMonth) + " " 33 | + currentDay + ", " 34 | + currentYear + " " 35 | + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0635_Geometry_area_of_a_pentagon.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: area of a pentagon) The area of a pentagon can be computed using 3 | * the following formula: 4 | * Area = (5 x s^2) / (4 x tan(Pi /5)) 5 | * Write a method that returns the area of a pentagon using the following header: 6 | * public static double area(double side) 7 | * Write a main method that prompts the user to enter the side of a pentagon and 8 | * displays its area. Here is a sample run: 9 | * Enter the side: 5.5 10 | * The area of the pentagon is 52.04444136781625 11 | * 12 | * Created by Sven on 07/27/19. 13 | */ 14 | package Chapter06; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0635_Geometry_area_of_a_pentagon { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter the side: "); 22 | double side = input.nextDouble(); 23 | System.out.println("The area of the pentagon is " + area(side)); 24 | } 25 | 26 | public static double area(double side) { 27 | return (5 * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 5)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0636_Geometry_area_of_a_regular_polygon.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Geometry: area of a regular polygon) A regular polygon is an n-sided polygon 3 | * in which all sides are of the same length and all angles have the same degree (i.e., 4 | * the polygon is both equilateral and equiangular). The formula for computing the 5 | * area of a regular polygon is 6 | * Area = (n x s^2) / (4 x tan(Pi / n)) 7 | * Write a method that returns the area of a regular polygon using the following header: 8 | * public static double area(int n, double side) 9 | * Write a main method that prompts the user to enter the number of sides and the 10 | * side of a regular polygon and displays its area. Here is a sample run: 11 | * Enter the number of sides: 5 12 | * Enter the side: 6.5 13 | * The area of the polygon is 72.69017017488385 14 | * 15 | * Created by Sven on 07/28/19. 16 | */ 17 | package Chapter06; 18 | 19 | import java.util.Scanner; 20 | 21 | public class Exercise0636_Geometry_area_of_a_regular_polygon { 22 | public static void main(String[] args) { 23 | Scanner input = new Scanner(System.in); 24 | System.out.print("Enter the number of sides: "); 25 | int n = input.nextInt(); 26 | System.out.print("Enter the side: "); 27 | double side = input.nextDouble(); 28 | System.out.println("The area of the polygon is " + area(n, side)); 29 | } 30 | 31 | public static double area(int n, double side) { 32 | return (n * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 5)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0637_Format_an_integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Format an integer) Write a method with the following header to format the integer 3 | * with the specified width. 4 | * public static String format(int number, int width) 5 | * The method returns a string for the number with one or more prefix 0s. The size of the 6 | * string is the width. For example, format(34, 4) returns 0034 and format(34, 7 | * 5) returns 00034. If the number is longer than the width, the method returns the 8 | * string representation for the number. For example, format(34, 1) returns 34. 9 | * Write a test program that prompts the user to enter a number and its width, and 10 | * displays a string returned by invoking format(number, width). 11 | * 12 | * Created by Sven on 07/28/19. 13 | */ 14 | package Chapter06; 15 | 16 | import java.util.Scanner; 17 | 18 | public class Exercise0637_Format_an_integer { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | System.out.print("Enter a number: "); 22 | int number = input.nextInt(); 23 | System.out.print("Enter a formatting width: "); 24 | int width = input.nextInt(); 25 | System.out.println("The formatted number: " + format(number, width)); 26 | } 27 | 28 | public static String format(int number, int width) { 29 | if (width <= getSize(number)) { 30 | return String.valueOf(number); 31 | } else { 32 | String result = ""; 33 | for (int i = 0; i < width - getSize(number); i++) { 34 | result += "0"; 35 | } 36 | result += String.valueOf(number); 37 | return result; 38 | } 39 | } 40 | 41 | public static int getSize(int d) { 42 | int size = 0; 43 | while (d > 0) { 44 | size++; 45 | d /= 10; 46 | } 47 | return size; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Chapter06/Exercise0638_Generate_random_characters.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Generate random characters) Use the methods in RandomCharacter in Listing 3 | * 6.10 to print 200 uppercase letters and then 200 single digits, printing ten per line. 4 | * 5 | * Created by Sven on 07/28/19. 6 | */ 7 | package Chapter06; 8 | 9 | public class Exercise0638_Generate_random_characters { 10 | public static void main(String[] args) { 11 | for (int i = 0; i < 200; i++) { 12 | if (i % 10 == 0 && i != 0) { 13 | System.out.println(); 14 | } 15 | System.out.print(getRandomUpperCaseLetter() + " "); 16 | } 17 | 18 | System.out.println("\n-------------------"); 19 | 20 | for (int i = 0; i < 200; i++) { 21 | if (i % 10 == 0 && i != 0) { 22 | System.out.println(); 23 | } 24 | System.out.print(getRandomDigitCharacter() + " "); 25 | } 26 | } 27 | 28 | /** 29 | * Generate a random character between ch1 and ch2 30 | */ 31 | public static char getRandomCharacter(char ch1, char ch2) { 32 | return (char) (ch1 + Math.random() * (ch2 - ch1 + 1)); 33 | } 34 | 35 | /** 36 | * Generate a random lowercase letter 37 | */ 38 | public static char getRandomLowerCaseLetter() { 39 | return getRandomCharacter('a', 'z'); 40 | } 41 | 42 | /** 43 | * Generate a random uppercase letter 44 | */ 45 | public static char getRandomUpperCaseLetter() { 46 | return getRandomCharacter('A', 'Z'); 47 | } 48 | 49 | /** 50 | * Generate a random digit character 51 | */ 52 | public static char getRandomDigitCharacter() { 53 | return getRandomCharacter('0', '9'); 54 | } 55 | 56 | /** 57 | * Generate a random character 58 | */ 59 | public static char getRandomCharacter() { 60 | return getRandomCharacter('\u0000', '\uFFFF'); 61 | } 62 | } -------------------------------------------------------------------------------- /src/Chapter07/Exercise0702_Comparing_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Comparing numbers) Write a program that reads 11 integers, compares each 3 | * integer with the 11th integer, and displays whether the integers are “greater”, 4 | * “smaller”, or “equal” to the 11th integer. 5 | * 6 | * Created by Sven on 07/30/19. 7 | */ 8 | package Chapter07; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0702_Comparing_numbers { 13 | public static void main(String[] args) { 14 | final int LENGTH = 11; 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter " + LENGTH + " numbers: "); 17 | int[] numbers = new int[LENGTH]; 18 | for (int i = 0; i < numbers.length; i++) { 19 | numbers[i] = input.nextInt(); 20 | } 21 | 22 | for (int i = 0; i < numbers.length; i++) { 23 | System.out.printf("Num #%d(%d), which is %s Num #%d(%d)\n", i, numbers[i], compareInt(numbers[i], 24 | numbers[numbers.length - 1]), numbers.length, numbers[numbers.length - 1]); 25 | } 26 | 27 | } 28 | 29 | public static String compareInt(int num1, int num2) { 30 | if (num1 == num2) { 31 | return "equal to"; 32 | } else if (num1 > num2) { 33 | return "greater than"; 34 | } else { 35 | return "smaller than"; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0703_Count_occurrence_of_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Count occurrence of numbers) Write a program that reads the integers between 3 | * 1 and 50 and counts the occurrences of each. Assume the input ends with 0. Here 4 | * is a sample run of the program: 5 | * Enter the integers between 1 and 50: 2 5 6 5 4 3 23 43 2 0 6 | * 2 occurs 2 times 7 | * 3 occurs 1 time 8 | * 4 occurs 1 time 9 | * 5 occurs 2 times 10 | * 6 occurs 1 time 11 | * 23 occurs 1 time 12 | * 43 occurs 1 time 13 | * 14 | * Created by Sven on 07/30/19. 15 | */ 16 | package Chapter07; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0703_Count_occurrence_of_numbers { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter the integers between 1 and 50: "); 24 | int[] occurrence = new int[50]; 25 | while (!input.hasNext("0")) { 26 | occurrence[input.nextInt()] += 1; 27 | } 28 | 29 | // Start from 1 30 | for (int i = 1; i < occurrence.length; i++) { 31 | if (occurrence[i] != 0) { 32 | System.out.printf("%d occurs %d %s\n", i, occurrence[i], (occurrence[i] == 1 ? "time" : "times")); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0704_Analyze_scores.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Analyze scores) Write a program that reads an unspecified number of scores and 3 | * determines how many scores are above or equal to the average, and how many 4 | * scores are below the average. Enter a negative number to signify the end of the 5 | * input. Assume the maximum number of scores is 100. 6 | * 7 | * Created by Sven on 07/30/19. 8 | */ 9 | package Chapter07; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0704_Analyze_scores { 14 | public static void main(String[] args) { 15 | final int MAX_LENGTH = 100; 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter scores (negative number signifies end): "); 18 | 19 | double[] scores = new double[MAX_LENGTH]; 20 | int numOfScores = 0; 21 | double sum = 0; 22 | for (; numOfScores < scores.length; numOfScores++) { 23 | double score = input.nextDouble(); 24 | if (score < 0) { 25 | break; 26 | } else { 27 | scores[numOfScores] = score; 28 | sum += score; 29 | } 30 | } 31 | 32 | double average = sum / numOfScores; 33 | int aboveOrEqualCount = 0; 34 | int belowCount = 0; 35 | for (int i = 0; i < numOfScores; i++) { 36 | if (scores[i] >= average) { 37 | aboveOrEqualCount++; 38 | } else { 39 | belowCount++; 40 | } 41 | } 42 | 43 | System.out.println("Average: " + average); 44 | System.out.println("Number of scores are above or equal to the average: " + aboveOrEqualCount); 45 | System.out.println("Number of scores are below the average: " + belowCount); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0705_The_number_of_even_numbers_and_odd_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (The number of even numbers and odd numbers) Write a program that reads ten 3 | * integers, and then display the number of even numbers and odd numbers. Assume 4 | * that the input ends with 0. Here is the sample run of the program. 5 | * Enter numbers: 1 2 3 2 1 6 3 4 5 2 3 6 8 9 9 0 6 | * The number of odd numbers: 8 7 | * The number of even numbers: 7 8 | * 9 | * Created by Sven on 07/30/19. 10 | */ 11 | package Chapter07; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0705_The_number_of_even_numbers_and_odd_numbers { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter numbers: "); 19 | int oddCount = 0; 20 | int evenCount = 0; 21 | while (!input.hasNext("0")) { 22 | if (input.nextInt() % 2 != 0) { 23 | oddCount++; 24 | } else { 25 | evenCount++; 26 | } 27 | } 28 | 29 | System.out.println("The number of odd numbers: " + oddCount); 30 | System.out.println("The number of even numbers: " + evenCount); 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0706_The_Sieve_of_Eratosthenes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (The Sieve of Eratosthenes) The Sieve of Eratosthenes is an algorithm that finds all 3 | * prime numbers up to a given limit, n. It works by creating an array of Booleans, 4 | * flag, of size n+1, initializing the array to true (assuming every number is a 5 | * prime number in the beginning), and iteratively traversing the numbers from 2 6 | * to n, setting the values of indices that are multiples of other numbers to false. 7 | * Write a program using the algorithm above, and display all the prime numbers 8 | * up to 50. 9 | * 10 | * Created by Sven on 08/05/19. 11 | */ 12 | package Chapter07; 13 | 14 | public class Exercise0706_The_Sieve_of_Eratosthenes { 15 | public static void main(String[] args) { 16 | final int NUM_LIMIT = 50; 17 | boolean[] flags = new boolean[NUM_LIMIT]; 18 | for (int i = 0; i < flags.length; i++) { 19 | flags[i] = true; 20 | } 21 | 22 | for (int i = 2; i < flags.length; i++) { 23 | if (flags[i] == true) { 24 | for (int j = 2; i * j < flags.length; j++) { 25 | flags[i * j] = false; 26 | } 27 | } 28 | } 29 | 30 | for (int i = 2; i < flags.length; i++) { 31 | if (flags[i] == true) { 32 | System.out.println(i); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0707_Count_single_digits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Count single digits) Write a program that generates 200 random integers between 3 | * 0 and 9 and displays the count for each number. (Hint: Use an array of ten integers, 4 | * say counts, to store the counts for the number of 0s, 1s, . . . , 9s.) 5 | * 6 | * Created by Sven on 08/05/19. 7 | */ 8 | package Chapter07; 9 | 10 | public class Exercise0707_Count_single_digits { 11 | public static void main(String[] args) { 12 | int[] counts = new int[10]; 13 | for (int i = 0; i < 200; i++) { 14 | counts[(int) (Math.random() * 10)]++; 15 | } 16 | for (int i = 0; i < counts.length; i++) { 17 | System.out.printf("Number %d appears %d times\n", i, counts[i]); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0708_Average_an_array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Average an array) Write two overloaded methods that return the average of an 3 | * array with the following headers: 4 | * public static int average(int[] array) 5 | * public static double average(double[] array) 6 | * Write a test program that prompts the user to enter 10 double values, invokes this 7 | * method, then displays the average value. 8 | * 9 | * Created by Sven on 08/05/19. 10 | */ 11 | package Chapter07; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0708_Average_an_array { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | double[] numbers = new double[10]; 19 | System.out.print("Enter ten numbers: "); 20 | for (int i = 0; i < numbers.length; i++) { 21 | numbers[i] = input.nextDouble(); 22 | } 23 | System.out.println("Average: " + average(numbers)); 24 | } 25 | 26 | public static int average(int[] array) { 27 | int sum = 0; 28 | for (int num : array) 29 | sum += num; 30 | return sum / array.length; 31 | } 32 | 33 | public static double average(double[] array) { 34 | double sum = 0; 35 | for (double num : array) 36 | sum += num; 37 | return sum / array.length; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0709_Find_the_largest_element.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the largest element) Write a method that finds the largest element in an array 3 | * of double values using the following header: 4 | * public static double max(double[] array) 5 | * Write a test program that prompts the user to enter ten numbers, invokes this 6 | * method to return the maximum value, and displays the maximum value. Here is 7 | * a sample run of the program: 8 | * Enter ten numbers: 1.9 2.5 3.7 2 1.5 6 3 4 5 2 9 | * The minimum number is: 6 10 | * 11 | * Created by Sven on 08/05/19. 12 | */ 13 | package Chapter07; 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise0709_Find_the_largest_element { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | double[] numbers = new double[10]; 21 | System.out.print("Enter ten numbers: "); 22 | for (int i = 0; i < numbers.length; i++) { 23 | numbers[i] = input.nextDouble(); 24 | } 25 | System.out.println("The maximum number is: " + max(numbers)); 26 | } 27 | 28 | public static double max(double[] array) { 29 | double max = array[0]; 30 | for (int i = 0; i < array.length; i++) { 31 | if (array[i] > max) { 32 | max = array[i]; 33 | } 34 | } 35 | return max; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0710_Find_the_index_of_the_largest_element.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Find the index of the largest element) Write a method that returns the index of the 3 | * largest element in an array of integers. If there is more than one element, return 4 | * the largest index. Use the following header: 5 | * public static int indexOfLargestElement(double[] array) 6 | * Write a test program that prompts the user to enter 10 numbers, invokes this 7 | * method to return the index of the largest element, and displays the index and the 8 | * element itself. 9 | * 10 | * Created by Sven on 08/05/19. 11 | */ 12 | package Chapter07; 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise0710_Find_the_index_of_the_largest_element { 17 | public static void main(String[] args) { 18 | Scanner input = new Scanner(System.in); 19 | double[] numbers = new double[10]; 20 | System.out.print("Enter ten numbers: "); 21 | for (int i = 0; i < numbers.length; i++) { 22 | numbers[i] = input.nextDouble(); 23 | } 24 | System.out.println("The maximum number is indexed as: " + indexOfLargestElement(numbers)); 25 | } 26 | 27 | public static int indexOfLargestElement(double[] array) { 28 | int indexOfLargestElement = 0; 29 | for (int i = 0; i < array.length; i++) { 30 | if (array[i] >= array[indexOfLargestElement]) { 31 | indexOfLargestElement = i; 32 | } 33 | } 34 | return indexOfLargestElement; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0712_Reverse_an_array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Reverse an array) The reverse method in Section 7.7 reverses an array by 3 | * copying it to a new array. Rewrite the method that reverses the array passed in 4 | * the argument and returns this array. Write a test program that prompts the user to 5 | * enter 10 numbers, invokes the method to reverse the numbers, and displays the 6 | * numbers. 7 | * 8 | * Created by Sven on 08/08/19. 9 | */ 10 | package Chapter07; 11 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise0712_Reverse_an_array { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter 10 numbers: "); 18 | int[] numbers = new int[10]; 19 | 20 | for (int i = 0; i < numbers.length; i++) { 21 | numbers[i] = input.nextInt(); 22 | } 23 | 24 | System.out.print("The reversed array is "); 25 | int[] result = reverse(numbers); 26 | for (int i = 0; i < result.length; i++) { 27 | System.out.print(result[i] + " "); 28 | } 29 | } 30 | 31 | public static int[] reverse(int[] list) { 32 | int[] result = new int[list.length]; 33 | 34 | for (int i = 0, j = result.length - 1; 35 | i < list.length; i++, j--) { 36 | result[j] = list[i]; 37 | } 38 | 39 | return result; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0713_Random_number_selector.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Random number selector) Write a method that returns a random number from a 3 | * list of numbers passed in the argument. The method header is specified as follows: 4 | * public static int getRandom(int... numbers) 5 | * 6 | * Created by Sven on 08/08/19. 7 | */ 8 | package Chapter07; 9 | 10 | public class Exercise0713_Random_number_selector { 11 | public static void main(String[] args) { 12 | int[] numbers = {141, 592, 653, 589, 793, 238, 462, 643, 383, 279}; 13 | System.out.println("The generated random number is " + getRandom(numbers)); 14 | } 15 | 16 | public static int getRandom(int[] numbers) { 17 | return numbers[(int) (Math.random() * numbers.length)]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0718_Bubble_sort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sort students) Write a program that prompts the user to enter the number of students, 3 | * the students’ names, and their scores and prints student names in decreasing 4 | * order of their scores. Assume the name is a string without spaces, use the Scanner’s 5 | * next() method to read a name. 6 | * 7 | * Created by Sven on 08/20/19. 8 | */ 9 | package Chapter07; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0718_Bubble_sort { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter 10 double numbers: "); 17 | double[] numbers = new double[10]; 18 | for (int i = 0; i < numbers.length; i++) { 19 | numbers[i] = input.nextDouble(); 20 | } 21 | double[] sortedList = bubbleSort(numbers); 22 | for (int i = 0; i < sortedList.length; i++) { 23 | System.out.print(sortedList[i] + " "); 24 | } 25 | } 26 | 27 | public static double[] bubbleSort(double[] list) { 28 | int n = list.length; 29 | for (int i = 0; i < n - 1; i++) { 30 | for (int j = 0; j < n - i - 1; j++) { 31 | if (list[j] > list[j + 1]) { 32 | // swap arr[j+1] and arr[i] 33 | double temp = list[j]; 34 | list[j] = list[j + 1]; 35 | list[j + 1] = temp; 36 | } 37 | } 38 | } 39 | return list; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0719_Sorted.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sorted?) Write the following method that returns true if the list is already sorted 3 | * in decreasing order. 4 | * public static boolean isSorted(int[] list) 5 | * Write a test program that prompts the user to enter a list and displays whether 6 | * the list is sorted or not. Here is a sample run. Note that the first number in the 7 | * input indicates the number of the elements in the list. This number is not part 8 | * of the list. 9 | * Enter list: 8 10 1 5 16 61 9 11 1 10 | * The list is not sorted 11 | * Enter list: 10 21 11 9 7 5 4 4 3 1 1 12 | * The list is already sorted 13 | * 14 | * Created by Sven on 08/20/19. 15 | */ 16 | package Chapter07; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0719_Sorted { 21 | public static void main(String[] args) { 22 | Scanner input = new Scanner(System.in); 23 | System.out.print("Enter list: "); 24 | int numberOfElements = input.nextInt(); 25 | int[] numbers = new int[numberOfElements]; 26 | for (int i = 0; i < numberOfElements; i++) { 27 | numbers[i] = input.nextInt(); 28 | } 29 | 30 | System.out.println(isSorted(numbers) ? "The list is already sorted" : "The list is not sorted"); 31 | } 32 | 33 | public static boolean isSorted(int[] list) { 34 | for (int i = 0; i < list.length - 1; i++) { 35 | if (list[i] < list[i + 1]) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0720_Descending_Bubble_Sort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Descending Bubble Sort) Modify the bubble sort method of Programming 3 | * Exercise 7.18, and sort the elements in the array in descending order instead of 4 | * ascending order. Write a test program that reads 10 double numbers, invokes the 5 | * method, and displays the sorted numbers in descending order. 6 | * 7 | * Created by Sven on 08/20/19. 8 | */ 9 | package Chapter07; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0720_Descending_Bubble_Sort { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter 10 double numbers: "); 17 | double[] numbers = new double[10]; 18 | for (int i = 0; i < numbers.length; i++) { 19 | numbers[i] = input.nextDouble(); 20 | } 21 | double[] sortedList = bubbleSort(numbers); 22 | for (int i = 0; i < sortedList.length; i++) { 23 | System.out.print(sortedList[i] + " "); 24 | } 25 | } 26 | 27 | public static double[] bubbleSort(double[] list) { 28 | int n = list.length; 29 | for (int i = 0; i < n - 1; i++) { 30 | for (int j = 0; j < n - i - 1; j++) { 31 | if (list[j] < list[j + 1]) { 32 | // swap arr[j+1] and arr[i] 33 | double temp = list[j]; 34 | list[j] = list[j + 1]; 35 | list[j + 1] = temp; 36 | } 37 | } 38 | } 39 | return list; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0721_Normalizing_integers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Normalizing integers) Write a program that prompts the user to enter 10 integers, 3 | * and normalizes the integers to be in the range of 0 to 1 by dividing every integer 4 | * with the largest integer. Display the 10 normalized real-valued numbers. 5 | * 6 | * Created by Sven on 08/22/19. 7 | */ 8 | package Chapter07; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0721_Normalizing_integers { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Enter ten numbers: "); 16 | double[] numbers = new double[10]; 17 | 18 | for (int i = 0; i < 10; i++) { 19 | numbers[i] = input.nextDouble(); 20 | } 21 | 22 | double[] normalizedNumbers = normalize(numbers); 23 | 24 | System.out.print("Normalized numbers: "); 25 | for (int i = 0; i < normalizedNumbers.length; i++) { 26 | System.out.print(normalizedNumbers[i] + " "); 27 | } 28 | } 29 | 30 | public static double[] normalize(double[] numbers) { 31 | double[] normalizedNumbers = new double[numbers.length]; 32 | double maxNumber = numbers[0]; 33 | for (int i = 0; i < numbers.length; i++) { 34 | if (numbers[i] > maxNumber) { 35 | maxNumber = numbers[i]; 36 | } 37 | } 38 | for (int i = 0; i < numbers.length; i++) { 39 | normalizedNumbers[i] = numbers[i] / maxNumber; 40 | } 41 | return normalizedNumbers; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0722_Count_the_number_of_vowels_in_a_string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Count the number of vowels in a string) Write a program that prompts the user to enter 3 | * a string, and counts and displays the number of both lowercase and uppercase vowels 4 | * in the string. 5 | * 6 | * Created by Sven on 08/22/19. 7 | */ 8 | package Chapter07; 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise0722_Count_the_number_of_vowels_in_a_string { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Enter a string: "); 16 | String str = input.nextLine(); 17 | char[] chars = str.toCharArray(); 18 | 19 | int vowelsCount = 0; 20 | for (int i = 0; i < chars.length; i++) { 21 | if (chars[i] == 'A' || chars[i] == 'E' || chars[i] == 'I' || chars[i] == 'O' || chars[i] == 'U' || 22 | chars[i] == 'a' || chars[i] == 'e' || chars[i] == 'i' || chars[i] == 'o' || chars[i] == 'u') { 23 | vowelsCount++; 24 | } 25 | } 26 | System.out.println("The number of vowels in the string is " + vowelsCount); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0723_Game_locker_puzzle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: locker puzzle) A school has 100 lockers and 100 students. All lockers are 3 | * closed on the first day of school. As the students enter, the first student, denoted 4 | * as S1, opens every locker. Then the second student, S2, begins with the second 5 | * locker, denoted as L2, and closes every other locker. Student S3 begins with the 6 | * third locker and changes every third locker (closes it if it was open and opens it if 7 | * it was closed). Student S4 begins with locker L4 and changes every fourth locker. 8 | * Student S5 starts with L5 and changes every fifth locker, and so on, until student 9 | * S100 changes L100. 10 | * After all the students have passed through the building and changed the lockers, 11 | * which lockers are open? Write a program to find your answer and display all open 12 | * locker numbers separated by exactly one space. 13 | * (Hint: Use an array of 100 Boolean elements, each of which indicates whether a 14 | * locker is open (true) or closed (false). Initially, all lockers are closed.) 15 | * 16 | * Created by Sven on 08/22/19. 17 | */ 18 | package Chapter07; 19 | 20 | public class Exercise0723_Game_locker_puzzle { 21 | public static void main(String[] args) { 22 | boolean[] lockers = new boolean[100]; 23 | for (int i = 1; i <= lockers.length; i++) { 24 | for (int j = i - 1; j < lockers.length; j += i) { 25 | lockers[j] = !lockers[j]; 26 | } 27 | } 28 | for (int i = 0; i < lockers.length; i++) { 29 | if (lockers[i]) { 30 | System.out.print((i + 1) + " "); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0726_Check_whether_array_is_sorted.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Check whether array is sorted) An array list is required to be sorted in ascending 3 | * order. Write a method that returns true if list is sorted, using the following header: 4 | * public static Bboolean isSorted(int[] list) 5 | * Write a test program that prompts the user to enter a list of integers. Note the first 6 | * number in the input indicates the number of elements in the list. This number is 7 | * not part of the list. 8 | * 9 | * Enter list: 5 2 5 6 9 10 10 | * The list is sorted 11 | * Enter list: 5 2 5 6 1 6 12 | * The list is not sorted. 13 | * 14 | * Created by Sven on 08/24/19. 15 | */ 16 | package Chapter07; 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise0726_Check_whether_array_is_sorted { 21 | public static void main(String[] args) { 22 | // Same logic as Exercise 0719 23 | Scanner input = new Scanner(System.in); 24 | System.out.print("Enter list: "); 25 | int numberOfElements = input.nextInt(); 26 | int[] numbers = new int[numberOfElements]; 27 | for (int i = 0; i < numberOfElements; i++) { 28 | numbers[i] = input.nextInt(); 29 | } 30 | 31 | System.out.println(isSorted(numbers) ? "The list is sorted" : "The list is not sorted"); 32 | } 33 | 34 | public static boolean isSorted(int[] list) { 35 | for (int i = 0; i < list.length - 1; i++) { 36 | if (list[i] > list[i + 1]) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0728_Math_permutations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Math: permutations) Write a program that prompts the user to enter four integers 3 | * and then displays all possible ways of arranging the four integers. 4 | * 5 | * Created by Sven on 08/24/19. 6 | */ 7 | package Chapter07; 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise0728_Math_permutations { 12 | public static void main(String[] args) { 13 | Scanner input = new Scanner(System.in); 14 | System.out.print("Enter four integers: "); 15 | int[] list = new int[4]; 16 | for (int i = 0; i < list.length; i++) { 17 | list[i] = input.nextInt(); 18 | } 19 | 20 | permutation(list, 4); 21 | } 22 | 23 | // print n! permutation of the elements of array a (not in order) 24 | private static void permutation(int[] a, int n) { 25 | if (n == 1) { 26 | for (int i = 0; i < a.length; i++) { 27 | System.out.print(a[i]); 28 | } 29 | System.out.println(); 30 | return; 31 | } 32 | for (int i = 0; i < n; i++) { 33 | swap(a, i, n - 1); 34 | permutation(a, n - 1); 35 | swap(a, i, n - 1); 36 | } 37 | } 38 | 39 | // swap the characters at indices i and j 40 | private static void swap(int[] a, int i, int j) { 41 | int c = a[i]; 42 | a[i] = a[j]; 43 | a[j] = c; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0729_Game_dice.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Game: dice) Suppose three dice are thrown at random. Write a program that 3 | * shows all possible permutations or configurations of the three dice that yield the 4 | * sum of nine. 5 | * 6 | * Created by Sven on 08/24/19. 7 | */ 8 | package Chapter07; 9 | 10 | public class Exercise0729_Game_dice { 11 | public static void main(String[] args) { 12 | // O(n^3) 13 | // can bu improved using Exercise 0728 14 | for (int i = 1; i <= 6; i++) { 15 | for (int j = 1; j <= 6; j++) { 16 | for (int k = 1; k <= 6; k++) { 17 | if (i + j + k == 9) { 18 | System.out.println(i + " " + j + " " + k); 19 | } 20 | } 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0730_Pattern_recognition_consecutive_four_equal_numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Pattern recognition: consecutive four equal numbers) Write the following method 3 | * that tests whether the array has four consecutive numbers with the same value: 4 | * public static boolean isConsecutiveFour(int[] values) 5 | * Write a test program that prompts the user to enter a series of integers and displays 6 | * it if the series contains four consecutive numbers with the same value. Your 7 | * program should first prompt the user to enter the input size—i.e., the number of 8 | * values in the series. Here are sample runs: 9 | * 10 | * Enter the number of values: 8 11 | * Enter the values: 3 4 5 5 5 5 4 5 12 | * The list has consecutive fours 13 | * Enter the number of values: 9 14 | * Enter the values: 3 4 5 5 6 5 5 4 5 15 | * The list has no consecutive fours 16 | * 17 | * Created by Sven on 08/24/19. 18 | */ 19 | package Chapter07; 20 | 21 | import java.util.Scanner; 22 | 23 | public class Exercise0730_Pattern_recognition_consecutive_four_equal_numbers { 24 | public static void main(String[] args) { 25 | Scanner input = new Scanner(System.in); 26 | System.out.print("Enter the number of values: "); 27 | int numOfValues = input.nextInt(); 28 | int[] list = new int[numOfValues]; 29 | System.out.print("Enter the values: "); 30 | for (int i = 0; i < list.length; i++) { 31 | list[i] = input.nextInt(); 32 | } 33 | 34 | System.out.println(isConsecutiveFour(list) ? "The list has consecutive fours" : "The list has no consecutive fours"); 35 | } 36 | 37 | public static boolean isConsecutiveFour(int[] values) { 38 | for (int i = 0; i < values.length - 4; i++) { 39 | if (values[i] == values[i + 1] && values[i] == values[i + 2] && values[i] == values[i + 3]) { 40 | return true; 41 | } 42 | } 43 | return false; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0733_Month_name.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Month name) Write a program that prompts the user to enter an integer between 3 | * 1 and 12 and then displays the name of the month that corresponds to the integer 4 | * entered by the user. For example, if the user enters three, the program should 5 | * display March. 6 | * 7 | * Created by Sven on 08/28/19. 8 | */ 9 | package Chapter07; 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise0733_Month_name { 14 | public static void main(String[] args) { 15 | final String[] MONTH_NAME = { 16 | "January", 17 | "February", 18 | "March", 19 | "April", 20 | "May", 21 | "June", 22 | "July", 23 | "August", 24 | "September", 25 | "October", 26 | "November", 27 | "December" 28 | }; 29 | Scanner input = new Scanner(System.in); 30 | int monthNum = 0; 31 | while (monthNum <= 0 || monthNum >= 13) { 32 | System.out.print("Enter a number (1-12): "); 33 | monthNum = input.nextInt(); 34 | } 35 | 36 | System.out.println(MONTH_NAME[monthNum - 1]); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Chapter07/Exercise0734_Sort_characters_in_a_string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * (Sort characters in a string) Write a method that returns a sorted string using the 3 | * following header: 4 | * public static String sort(String s) 5 | * For example, sort("acb") returns abc. 6 | * Write a test program that prompts the user to enter a string and displays the sorted 7 | * string. 8 | * 9 | * Created by Sven on 08/28/19. 10 | */ 11 | package Chapter07; 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise0734_Sort_characters_in_a_string { 16 | public static void main(String[] args) { 17 | Scanner input = new Scanner(System.in); 18 | 19 | System.out.print("Enter a string: "); 20 | String string = input.nextLine(); 21 | 22 | System.out.println(sort(string)); 23 | } 24 | 25 | public static String sort(String s) { 26 | char[] str = s.toCharArray(); 27 | 28 | for (int i = 0; i < str.length - 1; i++) { 29 | char min = str[i]; 30 | int minIndex = i; 31 | 32 | for (int j = i + 1; j < str.length; j++) { 33 | if (min > str[j]) { 34 | min = str[j]; 35 | minIndex = j; 36 | } 37 | } 38 | if (minIndex != i) { 39 | str[minIndex] = str[i]; 40 | str[i] = min; 41 | } 42 | } 43 | return new String(str); 44 | } 45 | } 46 | --------------------------------------------------------------------------------