├── .gitignore ├── Chp10 ├── Account.java ├── Course.java ├── Exercise_10_01.java ├── Exercise_10_03.java ├── Exercise_10_05.java ├── Exercise_10_06.java ├── Exercise_10_07.java ├── Exercise_10_09.java ├── Exercise_10_10.java ├── Exercise_10_16.java ├── LargeFactorial.java ├── Queue.java └── StackOfIntegers.java ├── Chp11 ├── Account.java ├── Exercise_11_01.java ├── Exercise_11_08.java ├── GeometricObject.java ├── Transaction.java └── Triangle.java ├── Chp12 ├── Exercise_12_02.java ├── Exercise_12_03.java ├── Exercise_12_05.java ├── Exercise_12_11.java ├── Exercise_12_12.java ├── Exercise_12_12_Test.java ├── Exercise_12_13.java ├── Exercise_12_14.java ├── GeometricObject.java ├── IllegalTriangleException.java ├── Loan.java ├── Triangle.java ├── numbers.txt └── text.txt ├── Chp13 ├── Circle.java ├── ComparableCircle.java ├── Exercise_13_01.java ├── Exercise_13_02.java ├── Exercise_13_03.java ├── Exercise_13_05.java ├── Exercise_13_06.java ├── GeometricObject.java ├── IllegalTriangleException.java └── Triangle.java ├── Chp17 ├── Copy.java ├── Exercise17_02.txt ├── Exercise_17_01.java ├── Exercise_17_02.java ├── Exercise_17_03.java └── TestFileStream.java ├── Chp2 ├── Exercise_02_01.java ├── Exercise_02_02.java ├── Exercise_02_03.java ├── Exercise_02_04.java ├── Exercise_02_06.java ├── Exercise_02_07.java ├── Exercise_02_08.java ├── Exercise_02_09.java ├── Exercise_02_10.java ├── Exercise_02_12.java ├── Exercise_02_13.java ├── Exercise_02_14.java ├── Exercise_02_15.java └── Exercise_02_22.java ├── Chp3 ├── BooleanTest.java ├── Exercise_03_01.java ├── Exercise_03_03.java ├── Exercise_03_04.java ├── Exercise_03_05.java ├── Exercise_03_06.java ├── Exercise_03_08.java ├── Exercise_03_09.java ├── Exercise_03_10.java ├── Exercise_03_11.java ├── Exercise_03_12.java ├── Exercise_03_14.java ├── SubtractionQuiz.java └── TestIOConsole.java ├── Chp4 ├── Exercise_04_01.java ├── Exercise_04_02.java ├── Exercise_04_13.java ├── Exercise_04_14.java ├── Exercise_04_16.java ├── Exercise_04_18.java ├── Exercise_04_19.java ├── Exercise_04_20.java ├── Exercise_04_21.java ├── Exercise_04_22.java ├── Exercise_04_23.java ├── Exercise_04_24.java └── Exercise_04_25.java ├── Chp5 ├── Exercise_05_01.java ├── Exercise_05_03.java ├── Exercise_05_05.java ├── Exercise_05_07.java └── Exercise_05_12.java ├── Chp6 ├── Exercise_06_01.java ├── Exercise_06_02.java ├── Exercise_06_03.java └── Exercise_06_05.java ├── Chp7 ├── BinarySearch.java ├── Exercise_07_01.java ├── Exercise_07_02.java ├── Exercise_07_03.java ├── Exercise_07_05.java ├── Exercise_07_07.java ├── Exercise_07_08.java ├── Exercise_07_09.java ├── Exercise_07_10.java ├── Exercise_07_13.java ├── LinearSearch.java └── SelectionSort.java ├── Chp8 ├── Exercise_08_01.java ├── Exercise_08_02.java ├── Exercise_08_04.java ├── Exercise_08_05.java ├── Exercise_08_06.java ├── Exercise_08_11.java └── Exercise_08_13.java ├── Chp9 ├── Exercise_09_03.java ├── Exercise_09_04.java ├── Exercise_09_05.java ├── Exercise_09_06_Test.java └── Exercise_09_07.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /Chp10/Account.java: -------------------------------------------------------------------------------- 1 | 2 | public class Account { 3 | private int id = 0; 4 | private double balance = 0.0; 5 | private static double annualInterestRate = 0.0; 6 | private java.util.Date dateCreated; 7 | 8 | public Account() { 9 | dateCreated = new java.util.Date(); 10 | } 11 | 12 | public Account(int id, double balance) { 13 | this(); 14 | this.id = id; 15 | this.balance = balance; 16 | } 17 | 18 | public int getId() { 19 | return this.id; 20 | } 21 | 22 | public double getBalance() { 23 | return this.balance; 24 | } 25 | 26 | public double getAnnualInterestRate() { 27 | return annualInterestRate; 28 | } 29 | 30 | public String getDateCreated() { 31 | return this.dateCreated.toString(); 32 | } 33 | 34 | public void setId(int id) { 35 | this.id = id; 36 | } 37 | 38 | public void setBalance(double balance) { 39 | this.balance = balance; 40 | } 41 | 42 | public void setAnnualInterestRate(double annualInterestRate) { 43 | this.annualInterestRate = annualInterestRate; 44 | } 45 | 46 | public double getMonthlyInterestRate() { 47 | return (annualInterestRate / 100) / 12 ; 48 | } 49 | 50 | public double getMonthlyInterest() { 51 | return balance * getMonthlyInterestRate(); 52 | } 53 | 54 | public void withdraw(double amount) { 55 | this.balance -= amount; 56 | } 57 | 58 | public void deposit(double amount) { 59 | this.balance += amount; 60 | } 61 | } -------------------------------------------------------------------------------- /Chp10/Course.java: -------------------------------------------------------------------------------- 1 | public class Course { 2 | private String courseName; 3 | private String[] students;; 4 | private int numberOfStudents; 5 | 6 | public Course(String courseName) { 7 | this.courseName = courseName; 8 | students = new String[1]; 9 | } 10 | 11 | public void addStudent(String student) { 12 | if (numberOfStudents >= students.length) { 13 | String[] temp = new String[students.length + 1]; 14 | System.arraycopy(students, 0, temp, 0, students.length); 15 | students = temp; 16 | } 17 | students[numberOfStudents] = student; 18 | numberOfStudents++; 19 | } 20 | 21 | public String[] getStudents() { 22 | return students; 23 | } 24 | 25 | public int getNumberOfStudents() { 26 | return numberOfStudents; 27 | } 28 | 29 | public String getCourseName() { 30 | return courseName; 31 | } 32 | 33 | public void dropStudent(String student) { 34 | int count = 0; 35 | String[] temp = new String[--numberOfStudents]; 36 | for (String s : students) { 37 | if (s.equals(student)) { 38 | continue; 39 | } 40 | temp[count] = s; 41 | count++; 42 | } 43 | students = temp; 44 | } 45 | 46 | public void clear() { 47 | String[] temp = new String[1]; 48 | students = temp; 49 | numberOfStudents = 0; 50 | } 51 | } -------------------------------------------------------------------------------- /Chp10/Exercise_10_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Design a class named Time. The class contains: 3 | The data fields hour, minute, and second that represent a time. 4 | A no-arg constructor that creates a Time object for the current time. (The 5 | values of the data fields will represent the current time.) 6 | A constructor that constructs a Time object with a specified elapsed time 7 | since midnight, January 1, 1970, in milliseconds. (The values of the data 8 | fields will represent this time.) 9 | A constructor that constructs a Time object with the specified hour, minute, 10 | and second. 11 | Three getter methods for the data fields hour, minute, and second, 12 | respectively. 13 | A method named setTime(long elapseTime) that sets a new time 14 | for the object using the elapsed time. For example, if the elapsed time is 15 | 555550000 milliseconds, the hour is 10, the minute is 19, and the second is 16 | 10. 17 | 18 | Write 19 | a test program that creates two Time objects (using new Time() and new 20 | Time(555550000)) and displays their hour, minute, and second in the format 21 | hour:minute:second. 22 | 23 | Hint: The first two constructors will extract the hour, minute, and second 24 | from the elapsed time. For the no-arg constructor, the current time can be 25 | obtained using System.currentTimeMillis() 26 | */ 27 | 28 | public class Exercise_10_01 { 29 | public static void main(String[] args) { 30 | Time time = new Time(555550000); 31 | Time time2 = new Time(); 32 | System.out.printf("%d:%d:%d%n%n", 33 | time2.getHour(), 34 | time2.getMinute(), 35 | time2.getSecond()); 36 | 37 | System.out.printf("%d:%d:%d%n%n", 38 | time.getHour(), 39 | time.getMinute(), 40 | time.getSecond()); 41 | 42 | time2.setTime(2432423534L); 43 | System.out.printf("%d:%d:%d%n%n", 44 | time2.getHour(), 45 | time2.getMinute(), 46 | time2.getSecond()); 47 | } 48 | } 49 | 50 | class Time { 51 | private int mHour; 52 | private int mMinute; 53 | private int mSecond; 54 | private long mTime; 55 | 56 | public Time() { 57 | mTime = System.currentTimeMillis(); 58 | } 59 | 60 | public Time(long time) { 61 | mTime = time; 62 | } 63 | public Time(int hour, int minute, int second) { 64 | mHour = hour; 65 | mMinute = minute; 66 | mSecond = second; 67 | } 68 | 69 | public void setTime(long elapsedTime) { 70 | mTime = elapsedTime; 71 | } 72 | 73 | 74 | public int getHour() { 75 | return (int)(mTime / (1000 * 60 * 60)) % 24; 76 | } 77 | 78 | public int getMinute() { 79 | return (int)(mTime / (1000 * 60)) % 60; 80 | } 81 | 82 | public int getSecond() { 83 | return (int)(mTime / 1000) % 60; 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /Chp10/Exercise_10_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Design a class named MyInteger. The class contains: 3 | An int data field named value that stores the int value represented by this 4 | object. 5 | A constructor that creates a MyInteger object for the specified int value. 6 | A getter method that returns the int value. 7 | The methods isEven(), isOdd(), and isPrime() that return true if the 8 | value in this object is even, odd, or prime, respectively. 9 | The static methods isEven(int), isOdd(int), and isPrime(int) that 10 | return true if the specified value is even, odd, or prime, respectively. 11 | The static methods isEven(MyInteger), isOdd(MyInteger), and 12 | isPrime(MyInteger) that return true if the specified value is even, odd, 13 | or prime, respectively. 14 | The methods equals(int) and equals(MyInteger) that return true if 15 | the value in this object is equal to the specified value. 16 | A static method parseInt(char[]) that converts an array of numeric 17 | characters to an int value. 18 | A static method parseInt(String) that converts a string into an int 19 | value. 20 | */ 21 | 22 | public class Exercise_10_03 { 23 | public static void main(String[] args) { 24 | MyInteger int1 = new MyInteger(23); 25 | MyInteger int2 = new MyInteger(56); 26 | MyInteger int3 = new MyInteger(2); 27 | MyInteger int4 = new MyInteger(23); 28 | 29 | System.out.printf("%d is prime? %s%n", int1.getValue(), int1.isPrime()); 30 | System.out.printf("%d is prime? %s%n", int2.getValue(), int2.isPrime()); 31 | System.out.printf("%d is prime? %s%n", int3.getValue(), int3.isPrime()); 32 | 33 | System.out.printf("%d is even? %s%n", int1.getValue(), int1.isEven()); 34 | System.out.printf("%d is even? %s%n", int2.getValue(), int2.isEven()); 35 | System.out.printf("%d is even? %s%n", int3.getValue(), int3.isEven()); 36 | 37 | System.out.printf("93 is odd? %s%n", MyInteger.isOdd(93)); 38 | 39 | System.out.printf("%d equals %d? %s%n", int1.getValue(), int4.getValue(), int1.equals(int4)); 40 | 41 | System.out.printf("%d%n", MyInteger.parseInt(new char[] {'1', '5', '6'})); 42 | System.out.printf("%d%n", MyInteger.parseInt("454")); 43 | } 44 | } 45 | 46 | 47 | class MyInteger { 48 | private int mValue; 49 | 50 | public MyInteger(int value) { 51 | mValue = value; 52 | } 53 | 54 | public int getValue() { 55 | return mValue; 56 | } 57 | 58 | public boolean isEven() { 59 | return (mValue % 2) == 0; 60 | } 61 | 62 | public boolean isOdd() { 63 | return (mValue % 2) == 1; 64 | } 65 | 66 | public boolean isPrime() { 67 | if (mValue == 1 || mValue == 2) { 68 | return true; 69 | } 70 | else { 71 | for (int i = 2; i < mValue; i++) { 72 | if (i % mValue == 0) return false; 73 | } 74 | } 75 | return true; 76 | } 77 | 78 | public static boolean isEven(int myInt) { 79 | return (myInt % 2) == 0; 80 | } 81 | 82 | public static boolean isOdd(int myInt) { 83 | return (myInt % 2) == 1; 84 | } 85 | 86 | public static boolean isPrime(int myInt) { 87 | if (myInt == 1 || myInt == 2) { 88 | return true; 89 | } 90 | else { 91 | for (int i = 2; i < myInt; i++) { 92 | if (i % myInt == 0) return false; 93 | } 94 | } 95 | return true; 96 | } 97 | 98 | public static boolean isEven(MyInteger myInt) { 99 | return myInt.isEven(); 100 | } 101 | 102 | public static boolean isOdd(MyInteger myInt) { 103 | return myInt.isOdd(); 104 | } 105 | 106 | public static boolean isPrime(MyInteger myInt) { 107 | return myInt.isPrime(); 108 | } 109 | 110 | public boolean equals(int testInt) { 111 | if (testInt == mValue) 112 | return true; 113 | return false; 114 | } 115 | 116 | public boolean equals(MyInteger myInt) { 117 | if (myInt.mValue == this.mValue) 118 | return true; 119 | return false; 120 | } 121 | 122 | public static int parseInt(char[] values) { 123 | int sum = 0; 124 | for (char i : values) { 125 | sum += Character.getNumericValue(i); 126 | } 127 | return sum; 128 | } 129 | 130 | public static int parseInt(String value) { 131 | return Integer.parseInt(value); 132 | } 133 | } -------------------------------------------------------------------------------- /Chp10/Exercise_10_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter 3 | a positive integer and displays all its smallest factors in decreasing order. For 4 | example, if the integer is 120, the smallest factors are displayed as 5, 3, 2, 2, 5 | 2. Use the StackOfIntegers class to store the factors (e.g., 2, 2, 2, 3, 5) and 6 | retrieve and display them in reverse order. 7 | */ 8 | import java.util.Scanner; 9 | 10 | 11 | public class Exercise_10_05 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int[] primes = new int[100]; 15 | //int[] valuesToCheck = new int[100]; 16 | StackOfIntegers soi = new StackOfIntegers(); 17 | 18 | System.out.print("Please enter a positive integer: "); 19 | int userVal = in.nextInt(); 20 | 21 | if (isPrime(userVal)){ 22 | System.out.printf("%d is a prime number.", userVal); 23 | } else { 24 | getFactors(userVal, soi); 25 | } 26 | 27 | int size = soi.getSize(); 28 | System.out.printf("The smallest prime factors of %d is ", userVal); 29 | for (int i = 0; i < size; i++) { 30 | System.out.printf("%d ", soi.pop()); 31 | } 32 | } 33 | 34 | public static void getFactors(int value, StackOfIntegers soi) { 35 | int[] values = new int[100]; 36 | values[0] = value; 37 | 38 | int valCount = 1; 39 | 40 | 41 | for (int potentialPrime : values) { 42 | if (isPrime(potentialPrime)) { 43 | soi.push(potentialPrime); 44 | break; 45 | } 46 | 47 | for (int i = 2; i < potentialPrime; i++) { 48 | if (potentialPrime % i == 0) { 49 | soi.push(i); 50 | values[valCount] = potentialPrime / i; 51 | break; 52 | } 53 | } 54 | valCount++; 55 | } 56 | } 57 | 58 | 59 | 60 | public static boolean isPrime(int value) { 61 | if (value == 1 || value == 2) { 62 | return true; 63 | } else { 64 | for (int i = 2; i < value; i++) { 65 | if (value % i == 0) 66 | return false; 67 | } 68 | } 69 | return true; 70 | } 71 | } 72 | 73 | 74 | -------------------------------------------------------------------------------- /Chp10/Exercise_10_06.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that displays all the prime 3 | numbers less than 120 in decreasing order. Use the StackOfIntegers class 4 | to store the prime numbers (e.g., 2, 3, 5, ...) and retrieve and display them in 5 | reverse order. 6 | */ 7 | 8 | public class Exercise_10_06 { 9 | public static void main(String[] args) { 10 | StackOfIntegers soi = new StackOfIntegers(); 11 | 12 | for (int i = 2; i < 120; i++) { 13 | if (isPrime(i)) 14 | soi.push(i); 15 | } 16 | 17 | int size = soi.getSize(); 18 | System.out.println("Prime numbers less than 120 are:"); 19 | for (int j = 0; j < size; j++) { 20 | System.out.printf("%d%s ", soi.pop(), j < size - 1 ? "," : ""); 21 | } 22 | } 23 | 24 | public static boolean isPrime(int value) { 25 | if (value == 1 || value == 2) { 26 | return true; 27 | } else { 28 | for (int i = 2; i < value; i++) { 29 | if (value % i == 0) 30 | return false; 31 | } 32 | } 33 | return true; 34 | } 35 | } -------------------------------------------------------------------------------- /Chp10/Exercise_10_07.java: -------------------------------------------------------------------------------- 1 | /* 2 | Use the Account class created in Programming Exercise 3 | 9.7 to simulate an ATM machine. Create ten accounts in an array with id 4 | 0, 1, . . . , 9, and initial balance $100. The system prompts the user to enter an 5 | id. If the id is entered incorrectly, ask the user to enter a correct id. Once an id 6 | is accepted, the main menu is displayed as shown in the sample run. You can 7 | enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for 8 | depositing money, and 4 for exiting the main menu. Once you exit, the system 9 | will prompt for an id again. Thus, once the system starts, it will not stop. 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise_10_07 { 15 | private static final Scanner in = new Scanner(System.in); 16 | 17 | public static void main(String[] args) { 18 | Account[] accounts = new Account[10]; 19 | for (int i = 1; i < 11; i++) { 20 | accounts[i - 1] = new Account(i, 100.0); 21 | } 22 | 23 | System.out.print("Enter an id (1 - 10): "); 24 | int id = in.nextInt(); 25 | 26 | if (id < 1 || id > 10) { 27 | id = incorrectId(id); 28 | } 29 | 30 | while (true) { 31 | menuDisplay(); 32 | System.out.print("Enter a choice: "); 33 | int choice = in.nextInt(); 34 | 35 | if (choice == 4) { 36 | System.out.printf("%nEnter an id (1 - 10): "); 37 | id = in.nextInt(); 38 | 39 | if (id < 1 || id > 10) { 40 | id = incorrectId(id); 41 | } 42 | } 43 | performChoice(id, choice, accounts); 44 | } 45 | } 46 | 47 | public static int incorrectId(int id) { 48 | //Scanner in = new Scanner(System.in); 49 | while (id < 1 || id > 10) { 50 | System.out.print("Please enter a valid id: "); 51 | id = in.nextInt(); 52 | System.out.println(); 53 | } 54 | return id; 55 | } 56 | 57 | public static void performChoice(int id, int choice, Account[] accounts) { 58 | //Scanner in = new Scanner(System.in); 59 | switch (choice) { 60 | case 1: 61 | System.out.printf("The balance is $%.1f%n", 62 | accounts[id - 1].getBalance()); 63 | break; 64 | case 2: 65 | System.out.print("Enter the amount to withdraw: "); 66 | accounts[id - 1].withdraw(in.nextDouble()); 67 | break; 68 | case 3: 69 | System.out.print("Enter the amount to deposit: "); 70 | accounts[id - 1].deposit(in.nextDouble()); 71 | break; 72 | default: 73 | break; 74 | } 75 | } 76 | 77 | public static void menuDisplay() { 78 | System.out.printf("%nMain menu%n"); 79 | System.out.println("1: check balance"); 80 | System.out.println("2: withdraw"); 81 | System.out.println("3: deposit"); 82 | System.out.println("4: exit"); 83 | } 84 | } -------------------------------------------------------------------------------- /Chp10/Exercise_10_09.java: -------------------------------------------------------------------------------- 1 | /* 2 | Revise the Course class as follows: 3 | The array size is fixed in Listing 10.6. Improve it to automatically increase 4 | the array size by creating a new larger array and copying the contents of the 5 | current array to it. 6 | Implement the dropStudent method. 7 | Add a new method named clear() that removes all students from the 8 | course. 9 | Write a test program that creates a course, adds three students, removes one, 10 | and displays the students in the course. 11 | */ 12 | 13 | public class Exercise_10_09 { 14 | public static void main(String[] args) { 15 | Course course = new Course("Intro to Java!"); 16 | 17 | course.addStudent("Mike Norman"); 18 | course.addStudent("Tom Jones"); 19 | course.addStudent("Rico Suave"); 20 | course.dropStudent("Mike Norman"); 21 | 22 | String[] students = course.getStudents(); 23 | System.out.printf("Number of students in %s: %d%n", 24 | course.getCourseName(), 25 | course.getNumberOfStudents()); 26 | 27 | for (String student : students) { 28 | System.out.printf("%s ", student); 29 | } 30 | System.out.println(); 31 | } 32 | } -------------------------------------------------------------------------------- /Chp10/Exercise_10_10.java: -------------------------------------------------------------------------------- 1 | /* 2 | Section 10.6 gives a class for Stack. Design a class named 3 | Queue for storing integers. Like a stack, a queue holds elements. In a stack, the 4 | elements are retrieved in a last-in first-out fashion. In a queue, the elements are 5 | retrieved in a first-in first-out fashion. The class contains: 6 | An int[] data field named elements that stores the int values in the 7 | queue. 8 | A data field named size that stores the number of elements in the queue. 9 | A constructor that creates a Queue object with default capacity 8. 10 | The method enqueue(int v) that adds v into the queue. 11 | The method dequeue() that removes and returns the element from the 12 | queue. 13 | The method empty() that returns true if the queue is empty. 14 | The method getSize() that returns the size of the queue. 15 | Draw an UML diagram for the class. Implement the class with the initial array 16 | size set to 8. The array size will be doubled once the number of the elements 17 | exceeds the size. After an element is removed from the beginning of the array, 18 | you need to shift all elements in the array one position the left. Write a test 19 | program that adds 20 numbers from 1 to 20 into the queue and removes these 20 | numbers and displays them. 21 | */ 22 | 23 | public class Exercise_10_10 { 24 | public static void main(String[] args) { 25 | 26 | Queue queue = new Queue(); 27 | 28 | for (int i = 0; i < 20; i++) { 29 | queue.enqueue(i + 1); 30 | } 31 | 32 | int queueSize = queue.getSize(); 33 | System.out.println("Values in the queue are: "); 34 | for (int j = 0; j < queueSize; j++) { 35 | System.out.printf("Value %d is: %d%n", 36 | j+1, queue.dequeue()); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Chp10/Exercise_10_16.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find the first ten numbers with 50 decimal digits that are 3 | divisible by 2 or 3. 4 | */ 5 | import java.math.BigInteger; 6 | 7 | public class Exercise_10_16 { 8 | public static void main(String[] args) { 9 | BigInteger bi = new BigInteger( 10 | "10000000000000000000000000000000000000000000000000"); 11 | bi.add(BigInteger.ONE); 12 | 13 | int count = 0; 14 | while(count < 10) { 15 | if (bi.remainder(new BigInteger("2")).equals(BigInteger.ZERO) || 16 | bi.remainder(new BigInteger("3")).equals(BigInteger.ZERO)){ 17 | System.out.println(bi); 18 | count++; 19 | } 20 | bi = bi.add(BigInteger.ONE); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Chp10/LargeFactorial.java: -------------------------------------------------------------------------------- 1 | import java.math.*; 2 | 3 | public class LargeFactorial { 4 | public static void main(String[] args) { 5 | System.out.println("50! is \n" + factorial(100)); 6 | } 7 | 8 | public static BigInteger factorial(long n) { 9 | BigInteger result = BigInteger.ONE; 10 | for (int i = 1; i <= n; i++) 11 | result = result.multiply(new BigInteger(i + "")); 12 | 13 | return result; 14 | } 15 | } -------------------------------------------------------------------------------- /Chp10/Queue.java: -------------------------------------------------------------------------------- 1 | 2 | class Queue { 3 | private int[] elements; 4 | private int size; 5 | 6 | public Queue() { 7 | elements = new int[8]; 8 | } 9 | 10 | public boolean empty() { 11 | return size == 0; 12 | } 13 | 14 | public int getSize() { 15 | return size; 16 | } 17 | 18 | public void enqueue(int v) { 19 | if (size >= elements.length) { 20 | int[] temp = new int[elements.length * 2]; 21 | System.arraycopy(elements, 0, temp, 0, elements.length); 22 | elements = temp; 23 | } 24 | elements[size] = v; 25 | size++; 26 | } 27 | 28 | public int dequeue() { 29 | // Using elements.length instead of size because the array length is 30 | // doubled when it needs to be increased instead of just being 31 | // increased by one. 32 | int[] temp = new int[elements.length - 1]; 33 | int returnVal = elements[0]; 34 | 35 | System.arraycopy(elements, 1, temp, 0, elements.length - 1); 36 | elements = temp; 37 | size--; 38 | return returnVal; 39 | } 40 | } -------------------------------------------------------------------------------- /Chp10/StackOfIntegers.java: -------------------------------------------------------------------------------- 1 | public class StackOfIntegers { 2 | private int[] elements; 3 | private int size; 4 | 5 | /** Construct a stack with the default capacity 16 */ 6 | public StackOfIntegers() { 7 | this(16); 8 | } 9 | 10 | /** Construct a stack with the specified maximum capacity */ 11 | public StackOfIntegers(int capacity) { 12 | elements = new int[capacity]; 13 | } 14 | 15 | /** Push a new integer into the top of the stack */ 16 | public int push(int value) { 17 | if (size >= elements.length) { 18 | int[] temp = new int[elements.length * 2]; 19 | System.arraycopy(elements, 0, temp, 0, elements.length); 20 | elements = temp; 21 | } 22 | 23 | return elements[size++] = value; 24 | } 25 | 26 | /** Return and remove the top element from the stack */ 27 | public int pop() { 28 | return elements[--size]; 29 | } 30 | 31 | /** Return the top element from the stack */ 32 | public int peek() { 33 | return elements[size - 1]; 34 | } 35 | 36 | /** Exercise03_21 whether the stack is empty */ 37 | public boolean empty() { 38 | return size == 0; 39 | } 40 | 41 | /** Return the number of elements in the stack */ 42 | public int getSize() { 43 | return size; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Chp11/Account.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class Account { 4 | private int id = 0; 5 | private double balance = 0.0; 6 | private static double annualInterestRate = 0.0; 7 | private java.util.Date dateCreated; 8 | private String name; 9 | private ArrayList transactions; 10 | 11 | public Account() { 12 | dateCreated = new java.util.Date(); 13 | transactions = new ArrayList(); 14 | } 15 | 16 | public Account(int id, double balance) { 17 | this(); 18 | this.id = id; 19 | this.balance = balance; 20 | } 21 | 22 | public Account(int id, double balance, String n) { 23 | this(id, balance); 24 | this.name = n; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String n) { 32 | name = n; 33 | } 34 | 35 | public ArrayList getTransactions() { 36 | return transactions; 37 | } 38 | 39 | public int getId() { 40 | return this.id; 41 | } 42 | 43 | public double getBalance() { 44 | return this.balance; 45 | } 46 | 47 | public double getAnnualInterestRate() { 48 | return annualInterestRate; 49 | } 50 | 51 | public String getDateCreated() { 52 | return this.dateCreated.toString(); 53 | } 54 | 55 | public void setId(int id) { 56 | this.id = id; 57 | } 58 | 59 | public void setBalance(double balance) { 60 | this.balance = balance; 61 | } 62 | 63 | public void setAnnualInterestRate(double annualInterestRate) { 64 | this.annualInterestRate = annualInterestRate; 65 | } 66 | 67 | public double getMonthlyInterestRate() { 68 | return (annualInterestRate / 100) / 12 ; 69 | } 70 | 71 | public double getMonthlyInterest() { 72 | return balance * getMonthlyInterestRate(); 73 | } 74 | 75 | public void withdraw(double amount) { 76 | this.balance -= amount; 77 | Transaction t = new Transaction('W', amount, this.balance, "Withdraw from account."); 78 | transactions.add(t); 79 | } 80 | 81 | public void deposit(double amount) { 82 | this.balance += amount; 83 | Transaction t = new Transaction('D', amount, this.balance, "Deposit to account."); 84 | transactions.add(t); 85 | } 86 | } -------------------------------------------------------------------------------- /Chp11/Exercise_11_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Design a class named Triangle that extends GeometricObject. The class contains: 3 | Threedouble data fields named side1,side2, and side3 with default 4 | values1.0 to denote three sides of the triangle. 5 | A no-arg constructor that creates a default triangle. 6 | A constructor that creates a triangle with the specified 7 | side1,side2, and side3. 8 | The accessor methods for all three data fields. 9 | A method named getArea() that returns the area of this triangle. 10 | A method named getPerimeter() that returns the perimeter of this triangle. 11 | A method named toString() that returns a string description for the triangle. 12 | 13 | For the formula to compute the area of a triangle, see Programming Exercise 14 | 2.19.ThetoString() method is implemented as follows: 15 | return"Triangle: side1 = " + side1 + " side2 = " + side2 +" side3 = " + side3; 16 | 17 | Draw the UML diagrams for the classes Triangle and GeometricObject and implement 18 | the classes. Write a test program that prompts the user to enter three sides of 19 | the triangle, a color, and a Boolean value to indicate whether the triangle is filled. 20 | The program should create a Triangle object with these sides and set thecolor 21 | and filled properties using the input. The program should display the area, 22 | perimeter, color, and true or false to indicate whether it is filled or no 23 | */ 24 | 25 | public class Exercise_11_01 { 26 | public static void main(String[] args) { 27 | java.util.Scanner in = new java.util.Scanner(System.in); 28 | 29 | System.out.print("Please enter the 3 sides of your triangle: "); 30 | double s1 = in.nextDouble(); 31 | double s2 = in.nextDouble(); 32 | double s3 = in.nextDouble(); 33 | System.out.print("Please enter the color: "); 34 | String color = in.next(); 35 | System.out.print("Is the triangle filled (true or false): "); 36 | boolean filled = in.nextBoolean(); 37 | 38 | Triangle t = new Triangle(s1, s2, s3); 39 | t.setColor(color); 40 | t.setFilled(filled); 41 | 42 | System.out.printf("Triangle perimeter: %.2f%n" + 43 | "Triangle area: %.2f%n" + 44 | "Triangle color: %s%n" + 45 | "Triangle filled? %s%n", 46 | t.getPerimeter(), 47 | t.getArea(), 48 | t.getColor(), 49 | t.isFilled()); 50 | 51 | 52 | } 53 | } 54 | 55 | -------------------------------------------------------------------------------- /Chp11/Exercise_11_08.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Exercise_11_08 { 4 | public static void main(String[] args) { 5 | Account ac = new Account(1122, 1000.0, "George"); 6 | ac.setAnnualInterestRate(1.5); 7 | 8 | ac.deposit(30.0); 9 | ac.deposit(40); 10 | ac.deposit(50); 11 | ac.withdraw(5); 12 | ac.withdraw(4); 13 | ac.withdraw(2); 14 | 15 | System.out.printf("%s Account #%d%nInterest rate: %.2f%n" + 16 | "Balance: %.2f%n" + 17 | "Transactions: %n", 18 | ac.getName(), 19 | ac.getId(), 20 | ac.getAnnualInterestRate(), 21 | ac.getBalance()); 22 | 23 | ArrayList transactions = ac.getTransactions(); 24 | for (Transaction trans : transactions) { 25 | System.out.printf("%nTransaction date: %s%n" + 26 | "Transaction type: %s%n" + 27 | "Transaction amount: %.2f%n" + 28 | "Transaction description: %s%n" + 29 | "Balance after transaction: %.2f%n", 30 | trans.getDate().toString(), 31 | trans.getType(), 32 | trans.getAmount(), 33 | trans.getDescription(), 34 | trans.getBalance()); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Chp11/GeometricObject.java: -------------------------------------------------------------------------------- 1 | // GeometricObject.java: The abstract GeometricObject class 2 | public abstract class GeometricObject { 3 | private String color = "white"; 4 | private boolean filled; 5 | 6 | /**Default construct*/ 7 | protected GeometricObject() { 8 | } 9 | 10 | /**Construct a geometric object*/ 11 | protected GeometricObject(String color, boolean filled) { 12 | this.color = color; 13 | this.filled = filled; 14 | } 15 | 16 | /**Getter method for color*/ 17 | public String getColor() { 18 | return color; 19 | } 20 | 21 | /**Setter method for color*/ 22 | public void setColor(String color) { 23 | this.color = color; 24 | } 25 | 26 | /**Getter method for filled. Since filled is boolean, 27 | so, the get method name is isFilled*/ 28 | public boolean isFilled() { 29 | return filled; 30 | } 31 | 32 | /**Setter method for filled*/ 33 | public void setFilled(boolean filled) { 34 | this.filled = filled; 35 | } 36 | 37 | /**Abstract method findArea*/ 38 | public abstract double getArea(); 39 | 40 | /**Abstract method getPerimeter*/ 41 | public abstract double getPerimeter(); 42 | } 43 | -------------------------------------------------------------------------------- /Chp11/Transaction.java: -------------------------------------------------------------------------------- 1 | 2 | public class Transaction { 3 | private java.util.Date mDate; 4 | private char mType; 5 | private double mAmount; 6 | private double mBalance; 7 | private String mDescription; 8 | 9 | public Transaction(char type, double amount, double balance, String description) { 10 | mType = type; 11 | mAmount = amount; 12 | mBalance = balance; 13 | mDescription = description; 14 | mDate = new java.util.Date(); 15 | } 16 | 17 | public char getType() { 18 | return mType; 19 | } 20 | 21 | public void setType(char type) { 22 | mType = type; 23 | } 24 | 25 | public double getAmount() { 26 | return mAmount; 27 | } 28 | 29 | public void setAmount(double amount) { 30 | mAmount = amount; 31 | } 32 | 33 | public double getBalance() { 34 | return mBalance; 35 | } 36 | 37 | public void setBalance(double balance) { 38 | mBalance = balance; 39 | } 40 | 41 | public String getDescription() { 42 | return mDescription; 43 | } 44 | 45 | public void setDescription(String description) { 46 | mDescription = description; 47 | } 48 | 49 | public java.util.Date getDate() { 50 | return mDate; 51 | } 52 | 53 | 54 | } -------------------------------------------------------------------------------- /Chp11/Triangle.java: -------------------------------------------------------------------------------- 1 | 2 | class Triangle extends GeometricObject { 3 | private double side1; 4 | private double side2; 5 | private double side3; 6 | 7 | public Triangle() { 8 | side1 = 1.0; 9 | side2 = 1.0; 10 | side3 = 1.0; 11 | } 12 | 13 | public Triangle(double s1, double s2, double s3) { 14 | this.side1 = s1; 15 | this.side2 = s2; 16 | this.side3 = s3; 17 | } 18 | 19 | public double getSideOne() { 20 | return this.side1; 21 | } 22 | 23 | public double getSideTwo() { 24 | return this.side2; 25 | } 26 | 27 | public double getSideThree() { 28 | return this.side3; 29 | } 30 | 31 | public double getArea() { 32 | double perimeter = this.side1 + this.side2 + this.side3; 33 | return Math.sqrt(perimeter * ( 34 | (perimeter - this.side1) * 35 | (perimeter - this.side2) * 36 | (perimeter - this.side3))); 37 | 38 | 39 | } 40 | 41 | public double getPerimeter() { 42 | return (this.side1 + this.side2 + this.side3); 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return "Triangle: side1 = " + this.side1 + " side2 = " + this.side2 + 48 | " side3 = " + this.side3; 49 | } 50 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to read two integers and displays their 3 | sum. Your program should prompt the user to read the number again if the 4 | input is incorrect 5 | */ 6 | 7 | public class Exercise_12_02 { 8 | public static void main(String[] args) { 9 | java.util.Scanner in = new java.util.Scanner(System.in); 10 | int n1 = 0; 11 | int n2 = 0; 12 | while(true) { 13 | System.out.print("Please enter in 2 integers to get their sum: "); 14 | try { 15 | n1 = in.nextInt(); 16 | n2 = in.nextInt(); 17 | 18 | break; 19 | } 20 | catch (java.util.InputMismatchException ime) { 21 | System.out.printf("You must enter 2 integers!%n%n"); 22 | in.nextLine(); 23 | } 24 | 25 | } 26 | System.out.printf("The sum is %d%n", (n1+n2)); 27 | } 28 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that meets the following requirements: 3 | Creates an array with 100 randomly chosen integers. 4 | Prompts the user to enter the index of the array, then displays 5 | the corre-sponding element value. If the specified index is out of bounds, 6 | display the messageOut of Bounds 7 | */ 8 | 9 | public class Exercise_12_03 { 10 | public static void main(String[] args) { 11 | java.util.Scanner in = new java.util.Scanner(System.in); 12 | int[] randomInts = new int[100]; 13 | 14 | for (int i = 0; i < 100; i++) { 15 | randomInts[i] = (int)(Math.random() * 101); 16 | } 17 | int arrayLength = randomInts.length; 18 | int val = 0; 19 | int valAtIndex = 0; 20 | 21 | System.out.print("Enter the index of the value you would like to see: "); 22 | try{ 23 | val = in.nextInt(); 24 | valAtIndex = randomInts[val - 1]; 25 | System.out.printf("The value at postition %d is %d%n", 26 | val, 27 | valAtIndex); 28 | } 29 | catch (java.util.InputMismatchException ime) { 30 | System.out.println("You must enter an integer!"); 31 | } 32 | catch (ArrayIndexOutOfBoundsException aiob) { 33 | System.out.println("You must enter an integer between 1 and 100."); 34 | 35 | } 36 | 37 | 38 | } 39 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Programming Exercise 11.1 defined the Triangle class with three sides. 3 | In a triangle, the sum of any two sides is greater than the other side. 4 | The Triangle class must adhere to this rule. Create the IllegalTriangleException 5 | class, and modify the constructor of the Triangle class to throw an 6 | IllegalTriangleException object if a triangle is created with sides that 7 | violate the rule, as follows:/** Construct a triangle with the specified sides 8 | 9 | public Triangle(double side1, double side2, double side3) 10 | throws IllegalTriangleException {// Implement it } 11 | 12 | */ 13 | 14 | public class Exercise_12_05 { 15 | public static void main(String[] args) { 16 | try{ 17 | Triangle t = new Triangle(0, 0, 1); 18 | } 19 | catch (IllegalTriangleException ite) { 20 | System.out.println("Error"); 21 | ite.printStackTrace(); 22 | } 23 | 24 | } 25 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_11.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that removes all the occurrences of a specified 3 | string from a text file. For example, invoking 4 | java Exercise12_11 John filename 5 | removes the string John from the specified file. Your program should get the 6 | arguments from the command line. 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise_12_11 { 12 | public static void main(String[] args) { 13 | String removalString = args[0]; 14 | String filename = args[1]; 15 | StringBuffer sb = new StringBuffer(); 16 | 17 | try( 18 | Scanner in = new Scanner(new java.io.File(filename)); 19 | ) { 20 | while(in.hasNext()) { 21 | String line = in.nextLine(); 22 | if (line.indexOf(removalString) != -1) { 23 | line.replace(removalString, ""); 24 | sb.append(line.replace(removalString, "")); 25 | }else { 26 | sb.append(line); 27 | } 28 | } 29 | System.out.println(sb.toString()); 30 | 31 | } 32 | catch (java.io.FileNotFoundException fnfe) { 33 | System.out.println("File not found."); 34 | } 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_12.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that converts the Java source 3 | code from the next-line brace style to the end-of-line brace style. 4 | 5 | Your program can be invoked from the command line with the Java sourcecode 6 | file as the argument. It converts the Java source code to a new format. For 7 | example, the following command converts the Java source-code file Test.java 8 | to the end-of-line brace style. 9 | */ 10 | import java.util.Scanner; 11 | import java.io.*; 12 | 13 | public class Exercise_12_12 { 14 | public static void main (String [] args) throws Exception { 15 | if (args.length != 1) { 16 | System.out.println("Use: java Exercise_12_12 Test.java"); 17 | System.exit(1); 18 | } 19 | 20 | File file = new File(args[0]); 21 | if (!file.exists()) { 22 | System.out.printf("%s does not exist.%n", args[0]); 23 | System.exit(2); 24 | } 25 | 26 | StringBuilder sb = new StringBuilder(); 27 | Scanner in = new Scanner(file); 28 | 29 | while(in.hasNext()) { 30 | String line = in.nextLine(); 31 | System.out.println(line); 32 | if ((line.trim()).isEmpty()) { 33 | sb.append("\r\n"); 34 | continue; 35 | } 36 | if ((line.trim()).charAt(0) == '{') { 37 | sb.append(" {"); 38 | if ((line.trim()).length() > 1) { 39 | sb.append("\r\n" + line.replace('{', ' ')); 40 | } 41 | } 42 | else { 43 | sb.append("\r\n" + line); 44 | } 45 | System.out.println(line); 46 | } 47 | in.close(); 48 | 49 | PrintWriter pw = new PrintWriter(file); 50 | pw.print(sb.toString()); 51 | pw.close(); 52 | } 53 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_12_Test.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Write a program that prompts the user to enter a letter and 4 | check whether the letter is a vowel or consonant. Here is a sample run: 5 | */ 6 | import java.util.Scanner; 7 | public class Exercise_12_12_Test { 8 | public static void main(String[] args) 9 | { 10 | Scanner in = new Scanner(System.in); 11 | 12 | System.out.print("Enter a letter : "); 13 | String letter = in.next(); 14 | char let = Character.toLowerCase(letter.charAt(0)); 15 | if (!Character.isLetter(let)) 16 | System.out.println(letter + " is invalid input."); 17 | else 18 | { 19 | switch(let) 20 | { 21 | case 'a': case 'e': case 'i': case 'o': case 'u': 22 | System.out.println(letter + " is a vowel"); 23 | break; 24 | default: 25 | System.out.println(letter + " is not a vowel"); 26 | } 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_13.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that will count 3 | the number of characters, words, and lines in a file. Words are separated by 4 | whitespace characters. The file name should be passed as a command-line 5 | argument, as shown in Figure 12.13. 6 | */ 7 | 8 | import java.util.Scanner; 9 | import java.io.File; 10 | 11 | public class Exercise_12_13 { 12 | public static void main(String[] args) throws Exception { 13 | if (args.length < 1) { 14 | System.out.println("Use: java Exercise_12_13 Loan.java"); 15 | System.exit(1); 16 | } 17 | 18 | File file = new File(args[0]); 19 | if (!file.exists()) { 20 | System.out.println("please include the source file"); 21 | System.exit(2); 22 | } 23 | 24 | Scanner in = new Scanner(file); 25 | long charCount = 0L; 26 | int lines = 0; 27 | int words = 0; 28 | 29 | while(in.hasNext()) { 30 | String line = in.nextLine(); 31 | 32 | String[] wordArray = line.split(" "); 33 | 34 | charCount += line.length(); 35 | lines += 1; 36 | words += wordArray.length; 37 | } 38 | System.out.printf("File %s has%n" + 39 | "%d characters%n" + 40 | "%d words%n" + 41 | "%d lines%n%n", 42 | args[0], charCount, words, lines); 43 | } 44 | } -------------------------------------------------------------------------------- /Chp12/Exercise_12_14.java: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose that a text file contains an unspecified number of scores separated by 3 | blanks. Write a program that prompts the user to enter the file, reads the 4 | scores from the file, and displays their total and averag 5 | */ 6 | 7 | import java.io.*; 8 | import java.util.Scanner; 9 | 10 | public class Exercise_12_14 { 11 | public static void main(String[] args) { 12 | 13 | System.out.print("Enter a filename of scores to read: "); 14 | Scanner console = new Scanner(System.in); 15 | File file = new File(console.next().trim()); 16 | 17 | try( 18 | Scanner in = new Scanner(file); 19 | ) { 20 | double sum = 0; 21 | int count = 0; 22 | 23 | while(in.hasNext()) { 24 | sum += in.nextDouble(); 25 | count++; 26 | } 27 | 28 | System.out.printf("Sum = %.2f, and average = %.2f%n", sum, sum / count); 29 | 30 | } catch (FileNotFoundException fnfe) { 31 | System.out.println("File not found."); 32 | } 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Chp12/GeometricObject.java: -------------------------------------------------------------------------------- 1 | // GeometricObject.java: The abstract GeometricObject class 2 | public abstract class GeometricObject { 3 | private String color = "white"; 4 | private boolean filled; 5 | 6 | /**Default construct*/ 7 | protected GeometricObject() { 8 | } 9 | 10 | /**Construct a geometric object*/ 11 | protected GeometricObject(String color, boolean filled) { 12 | this.color = color; 13 | this.filled = filled; 14 | } 15 | 16 | /**Getter method for color*/ 17 | public String getColor() { 18 | return color; 19 | } 20 | 21 | /**Setter method for color*/ 22 | public void setColor(String color) { 23 | this.color = color; 24 | } 25 | 26 | /**Getter method for filled. Since filled is boolean, 27 | so, the get method name is isFilled*/ 28 | public boolean isFilled() { 29 | return filled; 30 | } 31 | 32 | /**Setter method for filled*/ 33 | public void setFilled(boolean filled) { 34 | this.filled = filled; 35 | } 36 | 37 | /**Abstract method findArea*/ 38 | public abstract double getArea(); 39 | 40 | /**Abstract method getPerimeter*/ 41 | public abstract double getPerimeter(); 42 | } 43 | -------------------------------------------------------------------------------- /Chp12/IllegalTriangleException.java: -------------------------------------------------------------------------------- 1 | public class IllegalTriangleException extends Exception { 2 | 3 | public IllegalTriangleException(String message) { 4 | super("Exception: " + message); 5 | 6 | } 7 | 8 | } -------------------------------------------------------------------------------- /Chp12/Loan.java: -------------------------------------------------------------------------------- 1 | // Implements Seriablizable to support object IO 2 | public class Loan implements java.io.Serializable { 3 | private double annualInterestRate; 4 | private int numberOfYears; 5 | private double loanAmount; 6 | private java.util.Date loanDate; 7 | 8 | /** Default constructor */ 9 | public Loan() { 10 | this(2.5, 1, 1000); 11 | } 12 | 13 | /** Construct a loan with specified annual interest rate, 14 | number of years and loan amount 15 | */ 16 | public Loan(double annualInterestRate, int numberOfYears, 17 | double loanAmount) { 18 | this.annualInterestRate = annualInterestRate; 19 | this.numberOfYears = numberOfYears; 20 | this.loanAmount = loanAmount; 21 | loanDate = new java.util.Date(); 22 | } 23 | 24 | /** Return annualInterestRate */ 25 | public double getAnnualInterestRate() { 26 | return annualInterestRate; 27 | } 28 | 29 | /** Set a new annualInterestRate */ 30 | public void setAnnualInterestRate(double annualInterestRate) { 31 | this.annualInterestRate = annualInterestRate; 32 | } 33 | 34 | /** Return numberOfYears */ 35 | public int getNumberOfYears() { 36 | return numberOfYears; 37 | } 38 | 39 | /** Set a new numberOfYears */ 40 | public void setNumberOfYears(int numberOfYears) { 41 | this.numberOfYears = numberOfYears; 42 | } 43 | 44 | /** Return loanAmount */ 45 | public double getLoanAmount() { 46 | return loanAmount; 47 | } 48 | 49 | /** Set a newloanAmount */ 50 | public void setLoanAmount(double loanAmount) { 51 | this.loanAmount = loanAmount; 52 | } 53 | 54 | /** Find monthly payment */ 55 | public double getMonthlyPayment() { 56 | double monthlyInterestRate = annualInterestRate / 1200; 57 | double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 58 | (Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12))); 59 | return monthlyPayment; 60 | } 61 | 62 | /** Find total payment */ 63 | public double getTotalPayment() { 64 | double totalPayment = getMonthlyPayment() * numberOfYears * 12; 65 | return totalPayment; 66 | } 67 | 68 | /** Return loan date */ 69 | public java.util.Date getLoanDate() { 70 | return loanDate; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Chp12/Triangle.java: -------------------------------------------------------------------------------- 1 | 2 | class Triangle extends GeometricObject { 3 | private double side1; 4 | private double side2; 5 | private double side3; 6 | 7 | public Triangle() { 8 | side1 = 1.0; 9 | side2 = 1.0; 10 | side3 = 1.0; 11 | } 12 | 13 | public Triangle(double s1, double s2, double s3) 14 | throws IllegalTriangleException { 15 | if (s1 + s2 < s3 || s2 + s3 < s1 || s1 + s3 < s2) { 16 | throw new IllegalTriangleException("Any two sides added together" + 17 | " must be greater than the remaining side. NO side may equal 0!"); 18 | } 19 | this.side1 = s1; 20 | this.side2 = s2; 21 | this.side3 = s3; 22 | } 23 | 24 | public double getSideOne() { 25 | return this.side1; 26 | } 27 | 28 | public double getSideTwo() { 29 | return this.side2; 30 | } 31 | 32 | public double getSideThree() { 33 | return this.side3; 34 | } 35 | 36 | public double getArea() { 37 | double perimeter = this.side1 + this.side2 + this.side3; 38 | return Math.sqrt(perimeter * ( 39 | (perimeter - this.side1) * 40 | (perimeter - this.side2) * 41 | (perimeter - this.side3))); 42 | 43 | 44 | } 45 | 46 | public double getPerimeter() { 47 | return (this.side1 + this.side2 + this.side3); 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return "Triangle: side1 = " + this.side1 + " side2 = " + this.side2 + 53 | " side3 = " + this.side3; 54 | } 55 | } -------------------------------------------------------------------------------- /Chp12/numbers.txt: -------------------------------------------------------------------------------- 1 | 12 3.4 8 17 9 10 22 33 -------------------------------------------------------------------------------- /Chp12/text.txt: -------------------------------------------------------------------------------- 1 | this is john tome 2 | every time i look at this 3 | i say hey John, you know what? -------------------------------------------------------------------------------- /Chp13/Circle.java: -------------------------------------------------------------------------------- 1 | // Circle.java: The circle class that extends GeometricObject 2 | public class Circle extends GeometricObject { 3 | private double radius; 4 | 5 | /**Default constructor*/ 6 | public Circle() { 7 | this(1.0); 8 | } 9 | 10 | /**Construct circle with a specified radius*/ 11 | public Circle(double radius) { 12 | this(radius, "white", false); 13 | } 14 | 15 | /**Construct a circle with specified radius, filled, and color*/ 16 | public Circle(double radius, String color, boolean filled) { 17 | super(color, filled); 18 | this.radius = radius; 19 | } 20 | 21 | /**Return radius*/ 22 | public double getRadius() { 23 | return radius; 24 | } 25 | 26 | /**Set a new radius*/ 27 | public void setRadius(double radius) { 28 | this.radius = radius; 29 | } 30 | 31 | /**Implement the getArea method defined in GeometricObject*/ 32 | public double getArea() { 33 | return radius*radius*Math.PI; 34 | } 35 | 36 | /**Implement the getPerimeter method defined in GeometricObject*/ 37 | public double getPerimeter() { 38 | return 2*radius*Math.PI; 39 | } 40 | 41 | /**Override the equals() method defined in the Object class*/ 42 | public boolean equals(Circle circle) { 43 | return this.radius == circle.getRadius(); 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return "[Circle] radius = " + radius; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Chp13/ComparableCircle.java: -------------------------------------------------------------------------------- 1 | public class ComparableCircle extends Circle implements Comparable { 2 | private double radius; 3 | public ComparableCircle() { 4 | super(); 5 | } 6 | 7 | public ComparableCircle(double radius) { 8 | super(radius); 9 | } 10 | 11 | //Construct a circle with specified radius, filled, and color 12 | public ComparableCircle(double radius, String color, boolean filled) { 13 | super(radius, color, filled); 14 | } 15 | 16 | public int compareTo(ComparableCircle cc) { 17 | if (this.getArea() > cc.getArea()) { 18 | return 1; 19 | } else if (this.getArea() < cc.getArea()) { 20 | return -1; 21 | } else { 22 | return 0; 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Chp13/Exercise_13_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Design a new Triangle class that extends the abstract GeometricObject class 3 | implement the Triangle class. Write a test program that prompts the user to 4 | enter three sides of the triangle, a color, and a Boolean value to indicate 5 | whether the triangle is filled. The program should create a Triangle object 6 | with these sides and set the color and filled properties using the input. 7 | The program should display the area, perimeter, color, and true or false to 8 | indicate whether it is filled or not 9 | */ 10 | import java.util.Scanner; 11 | 12 | public class Exercise_13_01 { 13 | public static void main(String[] args) { 14 | 15 | Scanner in = new Scanner(System.in); 16 | System.out.print("Please enter 3 sides of a triangle, color and " + 17 | "whether it is filled or not (true false): "); 18 | double s1 = in.nextDouble(); 19 | double s2 = in.nextDouble(); 20 | double s3 = in.nextDouble(); 21 | String color = in.next(); 22 | boolean filled = in.nextBoolean(); 23 | 24 | Triangle t1 = null; 25 | 26 | try { 27 | t1 = new Triangle(s1, s2, s3, color, filled); 28 | } 29 | catch (IllegalTriangleException ite) { 30 | System.out.println(ite.toString()); 31 | } 32 | 33 | System.out.println(t1.toString()); 34 | System.out.printf("Triangle color: %s, Triangle filled: %s%n" + 35 | "Area: %.2f%n" + 36 | "Perimeter: %.2f%n%n", 37 | t1.getColor(), 38 | t1.isFilled(), 39 | t1.getArea(), 40 | t1.getPerimeter()); 41 | 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Chp13/Exercise_13_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write the following method that shuffles an ArrayList of numbers: 3 | public static void shuffle(ArrayList list) 4 | */ 5 | import java.util.ArrayList; 6 | 7 | public class Exercise_13_02 { 8 | public static void main(String[] args) { 9 | ArrayList list = new ArrayList(); 10 | 11 | list.add(21); 12 | list.add(2); 13 | list.add(24); 14 | list.add(67); 15 | list.add(1); 16 | list.add(3); 17 | list.add(53); 18 | 19 | shuffle(list); 20 | 21 | System.out.println(list.toString()); 22 | } 23 | 24 | public static void shuffle(ArrayList list) { 25 | for (int i = 0; i < list.size() - 1; i++) { 26 | int switchValue = (int) (Math.random() * list.size()); 27 | Number temp = list.get(switchValue); 28 | list.set(switchValue, list.get(i)); 29 | list.set(i, temp); 30 | } 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Chp13/Exercise_13_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write the following method that sorts an ArrayList of numbers. 3 | public static void sort(ArrayList list) 4 | */ 5 | 6 | import java.util.ArrayList; 7 | 8 | public class Exercise_13_03 { 9 | public static void main(String[] args) { 10 | ArrayList list = new ArrayList(); 11 | list.add(14); 12 | list.add(24); 13 | list.add(4); 14 | list.add(42); 15 | list.add(5); 16 | 17 | System.out.println("Unsorted: " + list.toString()); 18 | sort(list); 19 | System.out.println("Sorted: " + list.toString()); 20 | } 21 | 22 | public static void sort(ArrayList list) { 23 | for (int i = 0; i < list.size(); i++) { 24 | Number currentMin = list.get(i); 25 | int currentMinIndex = i; 26 | 27 | for (int j = i + 1; j < list.size(); j++) { 28 | if (currentMin.doubleValue() > list.get(j).doubleValue()) { 29 | currentMin = list.get(j); 30 | currentMinIndex = j; 31 | } 32 | } 33 | 34 | if (currentMinIndex != i) { 35 | list.set(currentMinIndex, list.get(i)); 36 | list.set(i, currentMin); 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chp13/Exercise_13_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Modify the GeometricObject class 3 | to implement the Comparable interface, and define a static max method in the 4 | GeometricObject class for finding the larger of two GeometricObject objects. 5 | Write a test program that uses the max method to find the larger of two 6 | circles and the larger of two rectangles. 7 | */ 8 | 9 | public class Exercise_13_05 { 10 | public static void main(String[] args) { 11 | GeometricObject c1 = new Circle(4); 12 | GeometricObject c2 = new Circle(5.3); 13 | 14 | GeometricObject largest = (Circle) GeometricObject.max(c1, c2); 15 | 16 | System.out.println("The larger circle is: " + 17 | largest.toString()); 18 | } 19 | } -------------------------------------------------------------------------------- /Chp13/Exercise_13_06.java: -------------------------------------------------------------------------------- 1 | /* 2 | Define a class named ComparableCircle 3 | that extends Circle and implements Comparable. Draw the UML diagram and 4 | implement the compareTo method to compare the circles on the basis of area. 5 | Write a test class to find the larger of two instances of ComparableCircle 6 | objects. 7 | */ 8 | 9 | public class Exercise_13_06 { 10 | public static void main(String[] args) { 11 | GeometricObject c1 = new ComparableCircle(3); 12 | GeometricObject c2 = new ComparableCircle(5.2); 13 | 14 | System.out.println("Biggest circle is: " + GeometricObject.max(c2, c1).toString()); 15 | } 16 | } -------------------------------------------------------------------------------- /Chp13/GeometricObject.java: -------------------------------------------------------------------------------- 1 | // GeometricObject.java: The abstract GeometricObject class 2 | public abstract class GeometricObject implements Comparable { 3 | private String color = "white"; 4 | private boolean filled; 5 | 6 | /**Default construct*/ 7 | protected GeometricObject() { 8 | } 9 | 10 | /**Construct a geometric object*/ 11 | protected GeometricObject(String color, boolean filled) { 12 | this.color = color; 13 | this.filled = filled; 14 | } 15 | 16 | public int compareTo(GeometricObject obj) { 17 | if (this.getArea() > obj.getArea()) { 18 | return 1; 19 | } 20 | else if(this.getArea() < obj.getArea()) { 21 | return -1; 22 | } 23 | else { 24 | return 0; 25 | } 26 | } 27 | 28 | /**Getter method for color*/ 29 | public String getColor() { 30 | return color; 31 | } 32 | 33 | /**Setter method for color*/ 34 | public void setColor(String color) { 35 | this.color = color; 36 | } 37 | 38 | /**Getter method for filled. Since filled is boolean, 39 | so, the get method name is isFilled*/ 40 | public boolean isFilled() { 41 | return filled; 42 | } 43 | 44 | /**Setter method for filled*/ 45 | public void setFilled(boolean filled) { 46 | this.filled = filled; 47 | } 48 | 49 | public static GeometricObject max(GeometricObject obj1, GeometricObject obj2) { 50 | int compare = obj1.compareTo(obj2); 51 | if (compare == 1) { 52 | return obj1; 53 | } else if (compare == -1) { 54 | return obj2; 55 | } else { 56 | return obj1; 57 | } 58 | 59 | } 60 | 61 | /**Abstract method findArea*/ 62 | public abstract double getArea(); 63 | 64 | /**Abstract method getPerimeter*/ 65 | public abstract double getPerimeter(); 66 | } 67 | -------------------------------------------------------------------------------- /Chp13/IllegalTriangleException.java: -------------------------------------------------------------------------------- 1 | public class IllegalTriangleException extends Exception { 2 | 3 | public IllegalTriangleException(String message) { 4 | super("Exception: " + message); 5 | 6 | } 7 | 8 | } -------------------------------------------------------------------------------- /Chp13/Triangle.java: -------------------------------------------------------------------------------- 1 | 2 | public class Triangle extends GeometricObject { 3 | private double mSide1; 4 | private double mSide2; 5 | private double mSide3; 6 | 7 | public Triangle() { 8 | super("Yellow", false); 9 | mSide1 = 1; 10 | mSide2 = 1; 11 | mSide3 = 1; 12 | } 13 | 14 | public Triangle(double s1, double s2, double s3, String color, boolean filled) 15 | throws IllegalTriangleException { 16 | 17 | super(color, filled); 18 | if (s1 + s2 < s3 || s2 + s3 < s1 || s1 + s3 < s2) { 19 | throw new IllegalTriangleException("Any two sides added together" + 20 | " must be greater than the remaining side. NO side may equal 0!"); 21 | } 22 | mSide1 = s1; 23 | mSide2 = s2; 24 | mSide3 = s3; 25 | } 26 | 27 | public double getSideOne() { 28 | return mSide1; 29 | } 30 | 31 | public double getSideTwo() { 32 | return mSide3; 33 | } 34 | 35 | public double getSideThree() { 36 | return mSide3; 37 | } 38 | 39 | public double getArea() { 40 | double perimeter = mSide1 + mSide2 + mSide3; 41 | return Math.sqrt(perimeter * ( 42 | (perimeter - mSide1) * 43 | (perimeter - mSide2) * 44 | (perimeter - mSide3))); 45 | } 46 | 47 | public double getPerimeter() { 48 | return (mSide1 + mSide2 + mSide3); 49 | } 50 | 51 | @Override 52 | public String toString() { 53 | return "Triangle: side1 = " + mSide1 + " side2 = " + mSide2 + 54 | " side3 = " + mSide3; 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /Chp17/Copy.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class Copy { 4 | public static void main(String[] args) throws IOException{ 5 | if (args.length != 2) { 6 | System.out.println("Usage: java Copy sourceFile targetFile"); 7 | System.exit(1); 8 | } 9 | 10 | File sourceFile = new File(args[0]); 11 | if (!sourceFile.exists()) { 12 | System.out.println("Sourcefile " + args[0] + " does not exist"); 13 | System.exit(2); 14 | } 15 | 16 | File targetFile = new File(args[1]); 17 | if (targetFile.exists()) { 18 | System.out.println("TargerFile " + args[1] + " already exists"); 19 | System.exit(3); 20 | } 21 | 22 | try ( 23 | BufferedInputStream input = 24 | new BufferedInputStream(new FileInputStream(args[0])); 25 | 26 | BufferedOutputStream output = 27 | new BufferedOutputStream(new FileOutputStream(args[1])); 28 | ) { 29 | int r = 0; 30 | int numberOfBytesRead = 0; 31 | while ((r = input.read()) != -1) { 32 | output.write(r); 33 | numberOfBytesRead++; 34 | } 35 | 36 | System.out.println(numberOfBytesRead + " bytes copied."); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Chp17/Exercise17_02.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mlnorman/Intro-To-Java-Programming/1ada4112b72e9245767cccdbe274c10c76d24bbe/Chp17/Exercise17_02.txt -------------------------------------------------------------------------------- /Chp17/Exercise_17_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to create a file named Exercise17_01.txt if 3 | it does not exist. Append new data to it if it already exists. Write 100 integers 4 | created randomly into the file using text I/O. Integers are separated by a space. 5 | */ 6 | 7 | import java.io.*; 8 | import java.util.Scanner; 9 | 10 | public class Exercise_17_01 { 11 | public static void main(String[] args) { 12 | 13 | try ( 14 | PrintWriter pw = new PrintWriter(new FileOutputStream(new File("Exercise17-01.txt"), true)); 15 | ) { 16 | for (int i = 0; i < 100; i++) { 17 | pw.print((int)(Math.random() * 100) + " "); 18 | } 19 | } 20 | catch (FileNotFoundException fnfe) { 21 | System.out.println("Cannot create the file."); 22 | fnfe.printStackTrace(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Chp17/Exercise_17_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to create a file named 3 | Exercise17_02.dat if it does not exist. Append new data to it if it already exists. 4 | Write 100 integers created randomly into the file using binary I/O. 5 | */ 6 | 7 | import java.io.*; 8 | 9 | public class Exercise_17_02 { 10 | public static void main(String[] args) { 11 | 12 | try ( 13 | DataOutputStream dos = new DataOutputStream(new FileOutputStream("Exercise17_02.txt", true)); 14 | ) { 15 | 16 | for (int i = 0; i < 100; i++) { 17 | dos.writeInt((int)(Math.random() * 10000)); 18 | } 19 | } 20 | catch (IOException ioe) { 21 | ioe.printStackTrace(); 22 | } 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Chp17/Exercise_17_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose a binary data file named 3 | Exercise17_03.dat has been created and its data are created using 4 | writeInt(int) in DataOutputStream. The file contains an unspecified 5 | number of integers. Write a program to find the sum of the integers. 6 | */ 7 | 8 | import java.io.*; 9 | 10 | public class Exercise_17_03 { 11 | public static void main(String[] args) { 12 | int sum = 0; 13 | 14 | try( 15 | DataInputStream dis = new DataInputStream(new FileInputStream("Exercise17_02.txt")); 16 | ) { 17 | while (true) { 18 | sum += dis.readInt(); 19 | } 20 | } 21 | catch (EOFException eof) { 22 | System.out.println("File reading complete."); 23 | } 24 | catch (IOException ioe) { 25 | ioe.printStackTrace(); 26 | } 27 | 28 | System.out.println("The sum of the values in the file is: " + sum); 29 | } 30 | } -------------------------------------------------------------------------------- /Chp17/TestFileStream.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | 4 | public class TestFileStream { 5 | public static void main(String[] args) throws IOException { 6 | try ( 7 | FileOutputStream output = new FileOutputStream("temp.dat"); 8 | ) { 9 | for (int i = 0; i < 10; i++) { 10 | output.write(i); 11 | } 12 | } 13 | 14 | try ( 15 | FileInputStream input = new FileInputStream("temp.dat") 16 | ) { 17 | int value = 0; 18 | while ((value = input.read()) != -1) { 19 | System.out.println(value); 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_01.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by mike on 2/19/2015. 3 | * 4 | * Convert Celcius to Fahrenheit 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class Exercise_02_01 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | 13 | System.out.print("Enter a degree in Celsius: "); 14 | 15 | double celsius = input.nextDouble(); 16 | double farhenheit = (9.0/5.0) * celsius + 32; 17 | 18 | System.out.println(celsius + " Celsius is " + farhenheit + " Farhenheit"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chp2/Exercise_02_02.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by admin on 2/19/2015. 3 | * Write a program that reads in the radius 4 | * and length of a cylinder and computes the area and volume using the following 5 | * formulas 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Exercise_02_02 { 11 | 12 | public static void main(String[] args) { 13 | final double PI = 3.1459; 14 | Scanner in = new Scanner(System.in); 15 | System.out.print("Enter the radius and length of a cylinder: "); 16 | String input = in.nextLine(); 17 | 18 | String[] split = input.split(" "); 19 | 20 | System.out.println(split[1]); 21 | double radius = Double.parseDouble(split[0]); 22 | double length = Double.parseDouble(split[1]); 23 | 24 | double area = radius * radius * PI; 25 | double volume = area * length; 26 | 27 | System.out.println("The area is " + area); 28 | System.out.println("The volume is " + volume); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Chp2/Exercise_02_03.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by admin on 3/11/2015. 3 | * 4 | * Conver feet to meters. 5 | */ 6 | import java.util.Scanner; 7 | 8 | public class Exercise_02_03 { 9 | 10 | public static void main(String[] args){ 11 | 12 | Scanner in = new Scanner(System.in); 13 | 14 | System.out.print("Enter a value for feet: "); 15 | double feet = in.nextDouble(); 16 | 17 | System.out.printf("%.2f feet is %.4f meters", feet, feet * 0.305); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chp2/Exercise_02_04.java: -------------------------------------------------------------------------------- 1 | /*********************** 2 | * Created by mike on 03/11/2015 3 | * 4 | * convert pounds to kilograms. 5 | *******************/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class Exercise_02_04{ 10 | public static void main(String[] args){ 11 | 12 | Scanner in = new Scanner(System.in); 13 | 14 | System.out.print("Enter the subtotal and a gratuity rate: "); 15 | 16 | double subtotal = in.nextDouble(); 17 | double gratuityRate = in.nextDouble(); 18 | 19 | double percentage = gratuityRate / 100.0; 20 | 21 | System.out.printf("The gratuity rate is $%.2f and total is $%.2f \n", subtotal * percentage, subtotal + 22 | (subtotal * percentage)); 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_06.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Created by mike 03/11/2015 3 | * 4 | * (Sum the digits in an integer) Write a program that reads an integer between 0 and 5 | * 1000 and adds all the digits in the integer. For example, if an integer is 932, the 6 | * sum of all its digits is 14. 7 | * 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise_02_06{ 13 | 14 | public static void main(String[] args){ 15 | 16 | Scanner in = new Scanner(System.in); 17 | 18 | System.out.print("Enter an integer between 0 and 1000: "); 19 | 20 | int userInput = in.nextInt(); 21 | 22 | int firstDigit = userInput % 10; // get last digit 23 | int firstExtract = userInput / 10; // remove last digit 24 | 25 | int secondDigit = firstExtract % 10; 26 | int secondExtract = firstExtract / 10; 27 | 28 | int thirdDigit = secondExtract % 10; 29 | int thirdExtract = secondExtract / 10; 30 | 31 | int lastDigit = thirdExtract % 10; 32 | 33 | int sum = firstDigit + secondDigit + thirdDigit + lastDigit; 34 | 35 | System.out.printf("The sum of digits is %d", sum); 36 | 37 | } 38 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_07.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 days for the minutes. 4 | * For simplicity, assume a year has 365 days. 5 | * 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Exercise_02_07{ 11 | 12 | public static void main(String[] args){ 13 | 14 | Scanner in = new Scanner(System.in); 15 | 16 | System.out.print("Enter the number of minutes: "); 17 | 18 | int numOfMinutes = in.nextInt(); 19 | 20 | int hour = 60; 21 | int day = 60 * 24; 22 | int year = day * 365; 23 | 24 | int numOfYears = numOfMinutes / year; 25 | int numOfDays = (numOfMinutes % year) / day; 26 | 27 | System.out.printf("%d minutes is approximately %d years and %d days.", numOfMinutes, numOfYears, numOfDays); 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_08.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * (Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays 4 | * the current time in GMT. Revise the program so that it prompts the user to enter 5 | * the time zone offset to GMT and displays the time in the specified time zone. 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Exercise_02_08{ 11 | public static void main(String[] args){ 12 | 13 | Scanner in = new Scanner(System.in); 14 | 15 | System.out.print("Enter the timezone offset to GMT: "); 16 | 17 | long offset = in.nextInt(); 18 | 19 | long currentTimeInMilliseconds = System.currentTimeMillis(); 20 | 21 | long totalSeconds = currentTimeInMilliseconds / 1000; 22 | long currentSecond = totalSeconds % 60; 23 | 24 | long totalMinutes = totalSeconds / 60; 25 | long currentMinute = totalMinutes % 60; 26 | 27 | long totalHours = totalMinutes / 60; 28 | long currentHour = (totalHours + offset) % 24; 29 | 30 | System.out.printf("The current time is %d:%d:%d\n", currentHour, currentMinute, currentSecond); 31 | 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_09.java: -------------------------------------------------------------------------------- 1 | /************************************* 2 | 3 | (Physics: acceleration) Average acceleration is defined as the change of velocity 4 | divided by the time taken to make the change, as shown in the following formula: 5 | a = 6 | v1 - v0 7 | t 8 | Write a program that prompts the user to enter the starting velocity v0 in meters/ 9 | second, the ending velocity v1 in meters/second, and the time span t in seconds, 10 | and displays the average acceleration. 11 | 12 | 13 | *********************************/ 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise_02_09{ 18 | 19 | public static void main(String[] args){ 20 | 21 | Scanner in = new Scanner(System.in); 22 | 23 | System.out.print("Enter v0, v1 and t: "); 24 | 25 | double v0 = in.nextDouble(); 26 | double v1 = in.nextDouble(); 27 | double t = in.nextDouble(); 28 | 29 | double acceleration = (v1 - v0) / t; 30 | 31 | System.out.printf("The average acceleration is %.4f", acceleration); 32 | } 33 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_10.java: -------------------------------------------------------------------------------- 1 | /******************************* 2 | 3 | Science: calculating energy) Write a program that calculates the energy needed 4 | to heat water from an initial temperature to a final temperature. Your program 5 | should prompt the user to enter the amount of water in kilograms and the initial 6 | and final temperatures of the water. The formula to compute the energy is 7 | Q = M * (finalTemperature – initialTemperature) * 4184 8 | where M is the weight of water in kilograms, temperatures are in degrees Celsius, 9 | and energy Q is measured in joules. 10 | 11 | ***********************************/ 12 | 13 | import java.util.Scanner; 14 | 15 | public class Exercise_02_10{ 16 | 17 | public static void main(String[] args){ 18 | 19 | Scanner in = new Scanner(System.in); 20 | 21 | System.out.print("Enter the amount of water in kilograms: "); 22 | double water = in.nextDouble(); 23 | 24 | System.out.print("Enter the initial temperature: "); 25 | double initTemp = in.nextDouble(); 26 | 27 | System.out.print("Enter the final temperature: "); 28 | double finalTemp = in.nextDouble(); 29 | 30 | double q = water * (finalTemp - initTemp) * 4184; 31 | 32 | System.out.println("The energy needed is " + q); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_12.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 = 6 | v2 7 | 2a 8 | Write a program that prompts the user to enter v in meters/second (m/s) and the 9 | acceleration a in meters/second squared (m/s2), and displays the minimum runway 10 | length. 11 | 12 | */ 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise_02_12{ 17 | 18 | public static void main(String[] args){ 19 | 20 | Scanner in = new Scanner(System.in); 21 | 22 | System.out.print("Enter speed and acceleration: "); 23 | double speed = in.nextDouble(); 24 | double acceleration = in.nextDouble(); 25 | 26 | double length = (speed * speed) / (2 * acceleration); 27 | 28 | System.out.printf("The minimum runway length for this airplane is %.2f\n", length); 29 | } 30 | 31 | } 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Chp2/Exercise_02_13.java: -------------------------------------------------------------------------------- 1 | /******************************** 2 | (Financial application: compound value) Suppose you save $100 each month 3 | into a savings account with the annual interest rate 5%. Thus, the monthly interest 4 | rate is 0.05/12 = 0.00417. After the first month, the value in the account 5 | becomes 6 | 100 * (1 + 0.00417) = 100.417 7 | After the second month, the value in the account becomes 8 | (100 + 100.417) * (1 + 0.00417) = 201.252 9 | After the third month, the value in the account becomes 10 | (100 + 201.252) * (1 + 0.00417) = 302.507 11 | and so on. 12 | Write a program that prompts the user to enter a monthly saving amount and 13 | displays the account value after the sixth month. (In Exercise 5.30, you will use a 14 | loop to simplify the code and display the account value for any month.) 15 | 16 | *******************************/ 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise_02_13{ 21 | public static void main(String[] args){ 22 | 23 | Scanner in = new Scanner(System.in); 24 | 25 | System.out.print("Enter the monthly saving amount: "); 26 | double savingAmount = in.nextInt(); 27 | 28 | double interestRateMonthly = 0.05/ 12.0; 29 | double firstMonth = 100 * (1 + 0.00417); 30 | double secondMonth = (100 + firstMonth) * (1 + 0.00417); 31 | double thirdMonth = (100 + secondMonth) * (1 + 0.00417); 32 | double forthMonth = (100 + thirdMonth) * (1 + 0.00417); 33 | double fifthMonth = (100 + forthMonth) * (1 + 0.00417); 34 | double sixthMonth = (100 + fifthMonth) * (1 + 0.00417); 35 | 36 | System.out.printf("After the sixth month, the account value is %.2f", sixthMonth); 37 | 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_14.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | (Health application: computing BMI) Body Mass Index (BMI) is a measure of 4 | health on weight. It can be calculated by taking your weight in kilograms and 5 | dividing by the square of your height in meters. Write a program that prompts the 6 | user to enter a weight in pounds and height in inches and displays the BMI. Note 7 | that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. 8 | 9 | */ 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise_02_14{ 14 | public static void main(String[] args){ 15 | 16 | Scanner in = new Scanner(System.in); 17 | 18 | System.out.print("Enter weight in pounds: "); 19 | double weight = in.nextDouble(); 20 | 21 | System.out.print("Enter height in inches: "); 22 | double height = in.nextDouble(); 23 | 24 | double weightInKg = weight * 0.45259237; 25 | double heightInM = height * 0.0254; 26 | 27 | System.out.printf("BMI is %.4f\n", weightInKg/(heightInM*heightInM)); 28 | } 29 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_15.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | (Geometry: distance of two points) Write a program that prompts the user to enter 4 | two points (x1, y1) and (x2, y2) and displays their distance between them. 5 | The formula for computing the distance is 2(x2 - x1)2 + (y2 - y1)2. Note that 6 | you can use Math.pow(a, 0.5) to compute 2a. 7 | 8 | 9 | */ 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise_02_15{ 14 | public static void main(String[] args){ 15 | 16 | Scanner in = new Scanner(System.in); 17 | 18 | System.out.print("Enter x1 and y1: "); 19 | double x1 = in.nextDouble(); 20 | double y1 = in.nextDouble(); 21 | 22 | System.out.print("Enter x2 and y2: "); 23 | double x2 = in.nextDouble(); 24 | double y2 = in.nextDouble(); 25 | 26 | double determinant = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2); 27 | double sqrRoot = Math.pow(determinant, 0.5); 28 | 29 | System.out.printf("The distance between two points is %f", sqrRoot); 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /Chp2/Exercise_02_22.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Exercise_02_22{ 4 | 5 | public static void main(String[] args){ 6 | 7 | Scanner in = new Scanner(System.in); 8 | 9 | System.out.print("Enter your amount in without a decimal. Ex Enter 1100 for $11.00: "); 10 | int amount = in.nextInt(); 11 | 12 | int cents = amount % 100; 13 | int dollars = amount / 100; 14 | 15 | int remaining = cents; 16 | 17 | int numOfQuarters = remaining / 25; 18 | remaining = remaining % 25; 19 | 20 | int numOfDimes = remaining / 10; 21 | remaining = remaining % 10; 22 | 23 | int numOfNickels = remaining / 5; 24 | remaining = remaining % 5; 25 | 26 | int numOfPennys = remaining / 1; 27 | 28 | 29 | System.out.printf("Your amount $%d.%d consists of\n", dollars, cents); 30 | System.out.println(" " + dollars + " dollars"); 31 | System.out.println(" " + numOfQuarters + " quarters"); 32 | System.out.println(" " + numOfDimes + " dimes"); 33 | System.out.println(" " + numOfNickels + " nickels"); 34 | System.out.println(" " + numOfPennys + " pennys"); 35 | } 36 | } -------------------------------------------------------------------------------- /Chp3/BooleanTest.java: -------------------------------------------------------------------------------- 1 | public class BooleanTest{ 2 | public static void main(String[] args){ 3 | 4 | boolean a = true; 5 | int c = (int)a; 6 | 7 | System.out.println(c); 8 | } 9 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a program that prompts the user to enter values for a, b, and c and displays 4 | the result based on the discriminant. If the discriminant is positive, display two 5 | roots. If the discriminant is 0, display one root. Otherwise, display The equation 6 | has no real roots 7 | 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise_03_01{ 13 | public static void main(String[] args){ 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | System.out.print("Enter a, b, c: "); 18 | 19 | double a = in.nextDouble(); 20 | double b = in.nextDouble(); 21 | double c = in.nextDouble(); 22 | 23 | double discriminant = Math.pow(Math.pow(b, 2) - (4 * a * c), 0.5); 24 | 25 | 26 | if (discriminant > 0){ 27 | double ans_1 = ((b*(-1)) + Math.pow((Math.pow(b,2) - 4 * a * c), 0.5)) / (2 * a); 28 | double ans_2 = ((b*(-1)) - Math.pow((Math.pow(b,2) - 4 * a * c), 0.5)) / (2 * a); 29 | 30 | System.out.printf("The equation has two roots %.5f and %.5f", ans_1, ans_2); 31 | 32 | }else if(discriminant == 0){ 33 | double ans = ((b*(-1)) + Math.pow((Math.pow(b,2) - 4 * a * c), 0.5)) / (2 * a); 34 | System.out.println("The equation has one root " + ans); 35 | }else{ 36 | System.out.println("The equation has no real roots"); 37 | } 38 | 39 | 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A linear equation can be solved using 4 | Cramer’s rule given in Programming Exercise 1.13. Write a program that prompts 5 | the user to enter a, b, c, d, e, and f and displays the result. If ad - bc is 0, report 6 | that The equation has no solution. 7 | 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise_03_03{ 13 | public static void main(String[] args){ 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | System.out.print("Enter a, b, c, d, e, f: "); 18 | 19 | double a = in.nextDouble(); 20 | double b = in.nextDouble(); 21 | double c = in.nextDouble(); 22 | double d = in.nextDouble(); 23 | double e = in.nextDouble(); 24 | double f = in.nextDouble(); 25 | 26 | if((a*d - b*c) == 0){ 27 | System.out.println("The equation has no solution."); 28 | }else{ 29 | double x = ((e * d) - (b * f)) / ((a * d) - (b * c)); 30 | double y = ((a * f) - (e * c)) / ((a * d) - (b * c)); 31 | 32 | System.out.printf("x is %.1f and y id %.1f", x, y); 33 | } 34 | 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Chp3/Exercise_03_04.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a program that randomly generates an integer between 1 4 | and 12 and displays the English month name January, February ..., December for 5 | the number 1, 2, 12 accordingly. 6 | */ 7 | 8 | import java.util.Random; 9 | 10 | public class Exercise_03_04{ 11 | public static void main(String[] args){ 12 | 13 | Random rand = new Random(); 14 | 15 | int random_month = rand.nextInt(12) + 1; 16 | 17 | switch(random_month){ 18 | case 1: System.out.println("January"); 19 | break; 20 | case 2: System.out.println("February"); 21 | break; 22 | case 3: System.out.println("March"); 23 | break; 24 | case 4: System.out.println("April"); 25 | break; 26 | case 5: System.out.println("May"); 27 | break; 28 | case 6: System.out.println("June"); 29 | break; 30 | case 8: System.out.println("August"); 31 | break; 32 | case 9: System.out.println("September"); 33 | break; 34 | case 10: System.out.println("October"); 35 | break; 36 | case 11: System.out.println("November"); 37 | break; 38 | case 12: System.out.println("December"); 39 | break; 40 | 41 | } 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter an integer for 3 | today’s day of the week (Sunday is 0, Monday is 1, …, and Saturday is 6). Also 4 | prompt the user to enter the number of days after today for a future day and display 5 | the future day of the week. 6 | 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise_03_05{ 12 | public static void main(String[] args){ 13 | 14 | Scanner in = new Scanner(System.in); 15 | 16 | System.out.printf("Enter todays date: "); 17 | int date = in.nextInt(); 18 | System.out.print("Enter the number of days elapsed since today: "); 19 | int elapsed = in.nextInt(); 20 | 21 | int future_date = (date + elapsed) % 7; 22 | String day_of_week = ""; 23 | 24 | switch(date){ 25 | case 0: day_of_week = "Sunday"; 26 | break; 27 | case 1: day_of_week = "Monday"; 28 | break; 29 | case 2: day_of_week = "Tuesday"; 30 | break; 31 | case 3: day_of_week = "Wednesday"; 32 | break; 33 | case 4: day_of_week = "Thursday"; 34 | break; 35 | case 5: day_of_week = "Friday"; 36 | break; 37 | case 6: day_of_week = "Saturday"; 38 | break; 39 | } 40 | 41 | if (future_date == 0){ 42 | System.out.printf("Todays is %s and the future day is Sunday", day_of_week); 43 | }else if(future_date == 1){ 44 | System.out.printf("Todays is %s and the future day is Monday", day_of_week); 45 | }else if(future_date == 2){ 46 | System.out.printf("Todays is %s and the future day is Tuesday", day_of_week); 47 | }else if(future_date == 3){ 48 | System.out.printf("Todays is %s and the future day is Wednesday", day_of_week); 49 | }else if(future_date == 4){ 50 | System.out.printf("Todays is %s and the future day is Thursday", day_of_week); 51 | }else if(future_date == 5){ 52 | System.out.printf("Todays is %s and the future day is Friday", day_of_week); 53 | }else if(future_date == 6){ 54 | System.out.printf("Todays is %s and the future day is Saturday", day_of_week); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_06.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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 | 7 | import java.util.Scanner; 8 | 9 | public class Exercise_03_06{ 10 | public static void main(String[] args){ 11 | Scanner in = new Scanner(System.in); 12 | 13 | final double KILOGRAMS_PER_POUND = 0.45359237; // Constant 14 | final double METERS_PER_INCH = 0.0254; // Constant 15 | final double FEET_PER_INCH = 0.0833333; // Constant 16 | 17 | System.out.printf("Enter weight in pounds: "); 18 | double weight = in.nextDouble(); 19 | System.out.printf("Enter feet: "); 20 | int feet = in.nextInt(); 21 | System.out.printf("Enter inches: "); 22 | int inches = in.nextInt(); 23 | 24 | double weightInKilograms = weight * KILOGRAMS_PER_POUND; 25 | double heightInMeters = (inches += FEET_PER_INCH) * METERS_PER_INCH; 26 | double bmi = weightInKilograms /(heightInMeters * heightInMeters); 27 | 28 | System.out.println("BMI is " + bmi); 29 | 30 | if (bmi < 18.5) 31 | System.out.println("Underweight"); 32 | else if (bmi < 25) 33 | System.out.println("Normal"); 34 | else if (bmi < 30) 35 | System.out.println("Overweight"); 36 | else 37 | System.out.println("Obese"); 38 | 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Chp3/Exercise_03_08.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a program that prompts the user to enter three integers 4 | and display the integers in non-decreasing order. 5 | 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Exercise_03_08{ 11 | public static void main(String[] args){ 12 | 13 | Scanner in = new Scanner(System.in); 14 | 15 | System.out.print("Enter 3 integers seperated by a space: "); 16 | int int_1 = in.nextInt(); 17 | int int_2 = in.nextInt(); 18 | int int_3 = in.nextInt(); 19 | 20 | if(int_1 < int_2 && int_1 < int_3 && int_2 < int_3){ 21 | System.out.println("Decreasing order: " + int_1 + " " + int_2 + " " + int_3); 22 | }else if(int_2 < int_1 && int_3 < int_2){ 23 | System.out.println("Decreasing order: " + int_3 + " " + int_2 + " " + int_1); 24 | }else if(int_2 > int_1 && int_2 > int_3 && int_1 < int_3){ 25 | System.out.println("Decreasing order: " + int_1 + " " + int_3 + " " + int_2); 26 | }else if(int_2 > int_1 && int_2 > int_3 && int_3 < int_1){ 27 | System.out.println("Decreasing order: " + int_2 + " " + int_1 + " " + int_3); 28 | }else if(int_2 > int_1 && int_2 > int_3 && int_3 > int_1){ 29 | System.out.println("Decreasing order: " + int_2 + " " + int_3 + " " + int_1); 30 | }else{ 31 | System.out.println("Decreasing order: " + int_3 + " " + int_1 + " " + int_2); 32 | } 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_09.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | An ISBN-10 (International Standard Book Number) 4 | consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum, 5 | which is calculated from the other nine digits using the following formula: 6 | (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + 7 | d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11 8 | If the checksum is 10, the last digit is denoted as X according to the ISBN-10 9 | convention. Write a program that prompts the user to enter the first 9 digits and 10 | displays the 10-digit ISBN (including leading zeros). Your program should read 11 | the input as an integer. 12 | 13 | */ 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise_03_09{ 18 | public static void main(String[] args){ 19 | 20 | Scanner in = new Scanner(System.in); 21 | 22 | System.out.print("Enter the 9 digit ISBN: "); 23 | int isbn = in.nextInt(); 24 | 25 | int digit_9 = isbn % 10; 26 | int current_length = isbn / 10; 27 | int digit_8 = current_length % 10; 28 | current_length = current_length / 10; 29 | int digit_7 = current_length % 10; 30 | current_length = current_length / 10; 31 | int digit_6 = current_length % 10; 32 | current_length = current_length / 10; 33 | int digit_5 = current_length % 10; 34 | current_length = current_length / 10; 35 | int digit_4 = current_length % 10; 36 | current_length = current_length / 10; 37 | int digit_3 = current_length % 10; 38 | current_length = current_length / 10; 39 | int digit_2 = current_length % 10; 40 | current_length = current_length / 10; 41 | int digit_1 = current_length % 10; 42 | current_length = current_length / 10; 43 | 44 | int checksum_int = (digit_1 * 1 + digit_2 * 2 + digit_3 * 3 + digit_4 * 4 + digit_5 * 5 + digit_6 * 6 + digit_7 * 7 + digit_8 * 8 + digit_9 * 9) % 11; 45 | 46 | boolean len = isbn < 100000000; 47 | 48 | if(checksum_int == 10){ 49 | if(len) 50 | System.out.println("The ISBN-10 number is 0" + isbn + "X"); 51 | else 52 | System.out.println("The ISBN-10 number is " + isbn + "X"); 53 | 54 | }else{ 55 | if(len) 56 | System.out.println("The ISBN-10 number is 0" + isbn + checksum_int); 57 | else 58 | System.out.println("The ISBN-10 number is " + isbn + checksum_int); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_10.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | import java.util.Scanner; 5 | 6 | public class Exercise_03_10{ 7 | public static void main(String[] args){ 8 | 9 | Scanner in = new Scanner(System.in); 10 | 11 | int number1 = (int)(Math.random() * 100); 12 | int number2 = (int)(Math.random() * 100); 13 | 14 | if(number1 < number2){ 15 | int temp = number1; 16 | number1 = number1; 17 | number2 = temp; 18 | } 19 | 20 | System.out.print("What is "+ number1 + " - " + number2 + "? "); 21 | int answer = in.nextInt(); 22 | 23 | if(number1 - number2 == answer) 24 | System.out.println("You are correct!"); 25 | else{ 26 | System.out.println("Your answer is incorrect."); 27 | System.out.print(number1 + " - " + number2 + " should be " + (number1 - number2)); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_11.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a program that prompts the user 4 | to enter the month and year and displays the number of days in the month. For 5 | example, if the user entered month 2 and year 2012, the program should display 6 | that February 2012 had 29 days. If the user entered month 3 and year 2015, the 7 | program should display that March 2015 had 31 days. 8 | 9 | */ 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise_03_11{ 14 | public static void main(String[] args){ 15 | 16 | Scanner in = new Scanner(System.in); 17 | System.out.print("Enter month number: "); 18 | int month = in.nextInt(); 19 | System.out.print("Enter year: "); 20 | int year = in.nextInt(); 21 | 22 | boolean leap_year = (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)); 23 | 24 | switch (month) { 25 | case 1: 26 | System.out.println("January " + year + " had 31 days."); 27 | break; 28 | case 2: 29 | if(leap_year) 30 | System.out.println("February " + year + " had 29 days."); 31 | else 32 | System.out.println("February " + year + " had 28 days."); 33 | break; 34 | case 3: 35 | System.out.println("March " + year + " had 31 days."); 36 | break; 37 | case 4: 38 | System.out.println("April " + year + " had 30 days."); 39 | break; 40 | case 5: 41 | System.out.println("May " + year + " had 31 days."); 42 | break; 43 | case 6: 44 | System.out.println("June " + year + " had 30 days."); 45 | break; 46 | case 7: 47 | System.out.println("July " + year + " had 31 days."); 48 | break; 49 | case 8: 50 | System.out.println("August " + year + " had 31 days."); 51 | break; 52 | case 9: 53 | System.out.println("September " + year + " had 30 days."); 54 | break; 55 | case 10: 56 | System.out.println("October " + year + " had 31 days."); 57 | break; 58 | case 11: 59 | System.out.println("November " + year + " had 30 days."); 60 | break; 61 | case 12: 62 | System.out.println("December " + year + " had 31 days."); 63 | break; 64 | default: 65 | System.out.println("Invalid month."); 66 | break; 67 | } 68 | 69 | 70 | 71 | } 72 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_12.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter a three-digit 3 | integer and determines whether it is a palindrome number. A number is palindrome 4 | if it reads the same from right to left and from left to right. Here is a sample 5 | run of this program 6 | 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise_03_12{ 12 | public static void main(String[] args){ 13 | 14 | Scanner in = new Scanner(System.in); 15 | 16 | System.out.print("Enter a three digit number: "); 17 | int user_input = in.nextInt(); 18 | 19 | int temp_remaning = 0; 20 | 21 | int d1 = user_input % 10; 22 | temp_remaning = user_input / 10; 23 | int d2 = temp_remaning % 10; 24 | int d3 = temp_remaning / 10; 25 | 26 | String rev = Integer.toString(d3) + Integer.toString(d2) + Integer.toString(d1); 27 | String original = Integer.toString(user_input); 28 | 29 | 30 | if(rev.equals(original)){ 31 | System.out.println(original + " is a palindrone"); 32 | }else{ 33 | System.out.println(original + " is not a palindrone"); 34 | 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Chp3/Exercise_03_14.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a program that lets the user guess whether the flip of 4 | a coin results in heads or tails. The program randomly generates an integer 0 or 1, 5 | which represents head or tail. The program prompts the user to enter a guess and 6 | reports whether the guess is correct or incorrect. 7 | 8 | */ 9 | import java.util.Scanner; 10 | import java.util.Random; 11 | 12 | public class Exercise_03_14{ 13 | public static void main(String[] args){ 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | Random random = new Random(); 18 | int coin_flip = random.nextInt(2); 19 | 20 | System.out.print("Coin flip. Enter 1 for heads, 0 for tails: "); 21 | int guess = in.nextInt(); 22 | 23 | if(guess == coin_flip){ 24 | System.out.println("Correct!"); 25 | }else{ 26 | System.out.println("Sorry, incorrect."); 27 | } 28 | 29 | 30 | } 31 | } -------------------------------------------------------------------------------- /Chp3/SubtractionQuiz.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 1. Generate two single-digit integers into number1 and number2. 4 | 2. If number1 < number2, swap number1 with number2. 5 | 3. Prompt the student to answer, "What is number1 – number2?" 6 | 4. Check the student’s answer and display whether the answer is correct. 7 | 8 | 9 | */ 10 | import java.util.Scanner; 11 | 12 | public class SubtractionQuiz{ 13 | public static void main(String[] args){ 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | int number1 = (int)(Math.random() * 10); 18 | int number2 = (int)(Math.random() * 10); 19 | 20 | if(number1 < number2){ 21 | int temp = number1; 22 | number1 = number1; 23 | number2 = temp; 24 | } 25 | 26 | System.out.print("What is "+ number1 + " - " + number2 + "?"); 27 | int answer = in.nextInt(); 28 | 29 | if(number1 - number2 == answer) 30 | System.out.println("You are correct!"); 31 | else{ 32 | System.out.println("Your answer is incorrect."); 33 | System.out.print(number1 + " - " + number2 + " should be " + (number1 - number2)); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Chp3/TestIOConsole.java: -------------------------------------------------------------------------------- 1 | /* 2 | Testing java.io.Console for output and input instead of 3 | System.out or Scanner/ 4 | */ 5 | 6 | import java.io.Console; 7 | 8 | public class TestIOConsole{ 9 | public static void main(String[] args){ 10 | Console console = System.console(); 11 | String name = console.readLine("What is your name? "); 12 | console.printf("Hi, %s", name); 13 | } 14 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_01.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Exercise_04_01{ 4 | public static void main(String[] args){ 5 | Scanner in = new Scanner(System.in); 6 | System.out.printf("Enter the lengh from the center to a vertec of a pentagon (integer): "); 7 | double radius = in.nextDouble(); 8 | 9 | double s = 2 * radius *Math.sin(Math.PI / 5); 10 | 11 | double area = (5 * (s * s)) / (4 * Math.tan(Math.PI / 5)); 12 | 13 | System.out.printf("%.2 f", area); 14 | 15 | } 16 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | (Geometry: great circle distance) The great circle distance is the distance between 3 | two points on the surface of a sphere. Let (x1, y1) and (x2, y2) be the geographical 4 | latitude and longitude of two points. The great circle distance between the two 5 | points can be computed using the following formula: 6 | d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) 7 | Write a program that prompts the user to enter the latitude and longitude of two 8 | points on the earth in degrees and displays its great circle distance. The average 9 | earth radius is 6,371.01 km. Note that you need to convert the degrees into radians 10 | using the Math.toRadians method since the Java trigonometric methods use 11 | radians. The latitude and longitude degrees in the formula are for north and west. 12 | Use negative to indicate south and east degrees. Here is a sample run: 13 | */ 14 | 15 | import java.util.Scanner; 16 | 17 | public class Exercise_04_02{ 18 | 19 | public static void main (String[] args){ 20 | Scanner in = new Scanner(System.in); 21 | 22 | System.out.print("Enter point 1 (latitude and longitude) in degrees: "); 23 | double point_1_latitude = in.nextDouble(); 24 | double point_1_longitude = in.nextDouble(); 25 | System.out.print("Enter point 2 (latitude and longitude) in degrees: "); 26 | double point_2_latitude = in.nextDouble(); 27 | double point_2_longitude = in.nextDouble(); 28 | 29 | double d = 6371.01 * Math.acos(( 30 | Math.sin(Math.toRadians(point_1_latitude)) * 31 | Math.sin(Math.toRadians(point_1_longitude))) + 32 | (Math.cos(Math.toRadians(point_1_latitude)) * 33 | Math.cos(Math.toRadians(point_1_longitude)) * 34 | Math.cos(Math.toRadians(point_2_longitude) - Math.toRadians(point_2_latitude)))); 35 | 36 | System.out.printf("The distance between the two points is %f km.%n", d); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Chp4/Exercise_04_13.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter a letter and 3 | check whether the letter is a vowel or consonant. Here is a sample run: 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | public class Exercise_04_13{ 9 | public static void main(String[] args) 10 | { 11 | Scanner in = new Scanner(System.in); 12 | 13 | System.out.print("Enter a letter : "); 14 | String letter = in.next(); 15 | char let = Character.toLowerCase(letter.charAt(0)); 16 | if (!Character.isLetter(let)) 17 | System.out.println(letter + " is invalid input."); 18 | else 19 | { 20 | switch(let) 21 | { 22 | case 'a': case 'e': case 'i': case 'o': case 'u': 23 | System.out.println(letter + " is a vowel"); 24 | break; 25 | default: 26 | System.out.println(letter + " is not a vowel"); 27 | } 28 | } 29 | 30 | } 31 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_14.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter a 3 | letter grade A, B, C, D, or F and displays its 4 | corresponding numeric value 4, 3, 2, 1, or 0. 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class Exercise_04_14{ 10 | public static void main(String[] args) 11 | { 12 | Scanner in = new Scanner(System.in); 13 | 14 | System.out.print("Enter a letter grade: "); 15 | char grade = in.nextLine().charAt(0); 16 | int val = 0; 17 | 18 | switch(Character.toUpperCase(grade)) 19 | { 20 | case 'A': 21 | val = 4; 22 | break; 23 | case 'B': 24 | val = 3; 25 | break; 26 | case 'C': 27 | val = 2; 28 | break; 29 | case 'D': 30 | val = 1; 31 | break; 32 | case 'F': 33 | val = 0; 34 | break; 35 | default: 36 | System.out.println(grade + " is an invalid grade"); 37 | break; 38 | } 39 | 40 | System.out.printf("The numeric value for grade %s is %d%n", Character.toUpperCase(grade), val); 41 | 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_16.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that displays a random uppercase letter 3 | using the Math.random() method. 4 | */ 5 | 6 | public class Exercise_04_16{ 7 | public static void main(String[] args) 8 | { 9 | //Get a random integer from 0 - 26 10 | int randomNumber = (int)(Math.random() * 27); 11 | 12 | String alphabet = "abcdefghijklmnopqrstuvwxyz"; 13 | // select a random character out of the alphabet and 14 | // display print upper case 15 | System.out.println(Character.toUpperCase(alphabet.charAt(randomNumber))); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_18.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter two 3 | characters and displays the major and status represented in the characters. The first 4 | character indicates the major and the second is number character 1, 2, 3, 4, which 5 | indicates whether a student is a freshman, sophomore, junior, or senior. Suppose 6 | the following chracters are used to denote the majors: 7 | M: Mathematics 8 | C: Computer Science 9 | I: Information Technology 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise_04_18{ 15 | public static void main(String[] args) 16 | { 17 | Scanner in = new Scanner(System.in); 18 | 19 | System.out.print("Enter two characters: "); 20 | String status = in.next(); 21 | 22 | char major = Character.toUpperCase(status.charAt(0)); 23 | char year = status.charAt(1); 24 | 25 | String courseName = ""; 26 | String yearName = ""; 27 | 28 | if (major == 'M' || major == 'I' || major == 'C') 29 | { 30 | switch(major) 31 | { 32 | case 'M': 33 | courseName = "Mathematics"; 34 | break; 35 | case 'C': 36 | courseName = "Computer Science"; 37 | break; 38 | case 'I': 39 | courseName = "Information Technology"; 40 | break; 41 | default: 42 | break; 43 | } 44 | 45 | switch(year) 46 | { 47 | case '1': 48 | yearName = "Freshman"; 49 | break; 50 | case '2': 51 | yearName = "Sophmore"; 52 | break; 53 | case '3': 54 | yearName = "Junior"; 55 | break; 56 | case '4': 57 | yearName = "Senior"; 58 | break; 59 | default: 60 | break; 61 | } 62 | System.out.printf("%s %s%n", courseName, yearName); 63 | } 64 | else{ 65 | System.out.printf("Invalid input.%n"); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_19.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | An ISBN-10 (International Standard Book Number) 4 | consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum, 5 | which is calculated from the other nine digits using the following formula: 6 | (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + 7 | d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11 8 | If the checksum is 10, the last digit is denoted as X according to the ISBN-10 9 | convention. Write a program that prompts the user to enter the first 9 digits and 10 | displays the 10-digit ISBN (including leading zeros). Your program should read 11 | the input as an integer. 12 | 13 | Rewrite the Programming Exercise 3.9 by entering the 14 | ISBN number as a string. 15 | 16 | */ 17 | 18 | import java.util.Scanner; 19 | 20 | public class Exercise_04_19{ 21 | public static void main(String[] args){ 22 | 23 | Scanner in = new Scanner(System.in); 24 | 25 | System.out.print("Enter the 9 digit ISBN: "); 26 | int isbn = Integer.parseInt(in.next()); 27 | 28 | int digit_9 = isbn % 10; 29 | int current_length = isbn / 10; 30 | int digit_8 = current_length % 10; 31 | current_length = current_length / 10; 32 | int digit_7 = current_length % 10; 33 | current_length = current_length / 10; 34 | int digit_6 = current_length % 10; 35 | current_length = current_length / 10; 36 | int digit_5 = current_length % 10; 37 | current_length = current_length / 10; 38 | int digit_4 = current_length % 10; 39 | current_length = current_length / 10; 40 | int digit_3 = current_length % 10; 41 | current_length = current_length / 10; 42 | int digit_2 = current_length % 10; 43 | current_length = current_length / 10; 44 | int digit_1 = current_length % 10; 45 | current_length = current_length / 10; 46 | 47 | int checksum_int = (digit_1 * 1 + digit_2 * 2 + digit_3 * 3 + digit_4 * 4 + digit_5 * 5 + digit_6 * 6 + digit_7 * 7 + digit_8 * 8 + digit_9 * 9) % 11; 48 | 49 | boolean len = isbn < 100000000; 50 | 51 | if(checksum_int == 10){ 52 | if(len) 53 | System.out.println("The ISBN-10 number is 0" + isbn + "X"); 54 | else 55 | System.out.println("The ISBN-10 number is " + isbn + "X"); 56 | 57 | }else{ 58 | if(len) 59 | System.out.println("The ISBN-10 number is 0" + isbn + checksum_int); 60 | else 61 | System.out.println("The ISBN-10 number is " + isbn + checksum_int); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_20.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter a string and displays 3 | its length and its first character. 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | public class Exercise_04_20{ 9 | public static void main(String[] args) 10 | { 11 | Scanner in = new Scanner(System.in); 12 | 13 | System.out.print("Please enter a string: "); 14 | String userInput = in.nextLine(); 15 | 16 | int inputLength = userInput.length(); 17 | char firstLetter = userInput.charAt(0); 18 | 19 | System.out.printf("Your string starts with \"%s\" and is %d characters long.%n", 20 | firstLetter, 21 | inputLength); 22 | } 23 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_21.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user to enter a Social Security 3 | number in the format DDD-DD-DDDD, where D is a digit. Your program should 4 | check whether the input is valid. 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class Exercise_04_21{ 10 | public static void main(String[] args) 11 | { 12 | Scanner in = new Scanner(System.in); 13 | 14 | System.out.print("Enter a SSN: "); 15 | String ssn = in.next(); 16 | 17 | for (int i = 0; i < ssn.length(); i++) 18 | { 19 | char ssnDigit = ssn.charAt(i); 20 | 21 | if (i == 3 || i == 6) 22 | { 23 | if (ssnDigit != '-') 24 | { 25 | System.out.printf("%s is an invalid social security number%n", ssn); 26 | System.exit(1); 27 | } 28 | } 29 | else 30 | { 31 | if (!Character.isDigit(ssnDigit)) 32 | { 33 | System.out.printf("%s is an invalid social security number%n", ssn); 34 | System.exit(1); 35 | } 36 | } 37 | } 38 | 39 | System.out.printf("%s is a valid social security number.%n", ssn); 40 | } 41 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_22.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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 | 6 | import java.util.Scanner; 7 | 8 | public class Exercise_04_22 { 9 | public static void main(String[] args) { 10 | 11 | Scanner in = new Scanner(System.in); 12 | 13 | System.out.print("Enter string s1: "); 14 | String s1 = in.nextLine(); 15 | 16 | System.out.print("Enter string s2: "); 17 | String s2 = in.nextLine(); 18 | 19 | if (s1.indexOf(s2) != -1) { 20 | System.out.printf("%s is a substring of %s%n", s2, s1); 21 | } 22 | else{ 23 | System.out.printf("%s is not a substring of %s%n", s2, s1); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_23.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads the following information 3 | and prints a payroll statement: 4 | Employee’s name (e.g., Smith) 5 | Number of hours worked in a week (e.g., 10) 6 | Hourly pay rate (e.g., 9.75) 7 | Federal tax withholding rate (e.g., 20%) 8 | State tax withholding rate (e.g., 9%) 9 | */ 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise_04_23{ 14 | public static void main(String[] args){ 15 | Scanner in = new Scanner(System.in); 16 | 17 | System.out.print("Enter employee's name: "); 18 | String name = in.nextLine(); 19 | System.out.print("Enter the number of hours worked in a week: "); 20 | double hoursWorked = in.nextDouble(); 21 | System.out.print("Enter hourly pay rate: "); 22 | double payRate = in.nextDouble(); 23 | System.out.print("Enter federal tax withholding rate: "); 24 | double federalTax = in.nextDouble(); 25 | System.out.print("Enter state tax withholding rate: "); 26 | double stateTax = in.nextDouble(); 27 | 28 | double fWithholding = federalTax * payRate * hoursWorked; 29 | double sWithholding = stateTax * payRate * hoursWorked; 30 | double grossPay = payRate * hoursWorked; 31 | 32 | System.out.printf("Employee Name: %s%nHours Worked: %.1f%nPay Rate: $%.2f%n" + 33 | "Gross Pay: $%.2f%nDeductions:%n Federal Withholding (%.1f%%): $%.2f%n" + 34 | " State Withholding (%.1f%%): $%.2f%n Total Deduction: $%.2f%n" + 35 | "Net Pay: $%.2f%n", 36 | name, 37 | hoursWorked, 38 | payRate, 39 | grossPay, 40 | federalTax * 100, 41 | fWithholding, 42 | stateTax * 100, 43 | sWithholding, 44 | fWithholding + sWithholding, 45 | grossPay - fWithholding - sWithholding); 46 | } 47 | } -------------------------------------------------------------------------------- /Chp4/Exercise_04_24.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Write a program that prompts the user to enter three cities and 4 | displays them in ascending order. 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class Exercise_04_24{ 10 | public static void main(String[] args){ 11 | Scanner in = new Scanner(System.in); 12 | 13 | System.out.print("Enter the first city: "); 14 | String firstCity = in.nextLine(); 15 | System.out.print("Enter the second city: "); 16 | String secondCity = in.nextLine(); 17 | System.out.print("Enter the third city: "); 18 | String thirdCity = in.nextLine(); 19 | 20 | if (firstCity.toUpperCase().compareTo(secondCity.toUpperCase()) > 0){ 21 | String temp = firstCity; 22 | firstCity = secondCity; 23 | secondCity = temp; 24 | } 25 | 26 | if (secondCity.toUpperCase().compareTo(thirdCity.toUpperCase()) > 0){ 27 | String temp = secondCity; 28 | secondCity = thirdCity; 29 | thirdCity = temp; 30 | } 31 | 32 | if (firstCity.toUpperCase().compareTo(secondCity.toUpperCase()) > 0){ 33 | String temp = firstCity; 34 | firstCity = secondCity; 35 | secondCity = temp; 36 | } 37 | 38 | System.out.printf("The cities in alphabetical order are %s, %s, %s%n", 39 | firstCity, secondCity, thirdCity); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Chp4/Exercise_04_25.java: -------------------------------------------------------------------------------- 1 | /* 2 | Assume a vehicle plate number consists of three 3 | uppercase letters followed by four digits. Write a program to generate a plate 4 | number. 5 | */ 6 | 7 | public class Exercise_04_25{ 8 | public static void main(String[] args){ 9 | String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 10 | 11 | int num1 = (int)(Math.random() * 10); 12 | int num2 = (int)(Math.random() * 10); 13 | int num3 = (int)(Math.random() * 10); 14 | int num4 = (int)(Math.random() * 10); 15 | 16 | int char1 = (int) (Math.random() * 10); 17 | int char2 = (int) (Math.random() * 10); 18 | int char3 = (int) (Math.random() * 10); 19 | 20 | System.out.printf("%s%s%s%d%d%d%d%n", 21 | alphabet.charAt(char1), 22 | alphabet.charAt(char2), 23 | alphabet.charAt(char3), 24 | num1, 25 | num2, 26 | num3, 27 | num4); 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /Chp5/Exercise_05_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads an unspecified number of integers, determines how many 3 | positive and negative values have been read, and computes the total and average of 4 | the input values (not counting zeros). Your program ends with the input 0. Display 5 | the average as a floating-point number. 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Exercise_05_01{ 11 | public static void main(String[] args){ 12 | Scanner in = new Scanner(System.in); 13 | 14 | System.out.print("Enter a series of integers seperated by a space (ex. 1 2 -5 3 0), the input ends if it is 0: "); 15 | int val = in.nextInt(); 16 | double total = 0; 17 | int numOfPos = 0; 18 | int numOfNeg = 0; 19 | double avg = 0; 20 | int count = 0; 21 | 22 | while (val != 0){ 23 | total += val; 24 | 25 | if (val > 0) 26 | numOfPos += 1; 27 | else 28 | numOfNeg += 1; 29 | 30 | count += 1; 31 | 32 | val = in.nextInt(); 33 | } 34 | 35 | avg = total / (double) count; 36 | 37 | System.out.printf("The number of positives is %d%nThe number of negatives is %d%n" + 38 | "The total is %.2f%nThe average is %.2f%n", numOfPos, numOfNeg, total, avg); 39 | } 40 | } -------------------------------------------------------------------------------- /Chp5/Exercise_05_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that displays the follow-ing table 3 | (note that 1 kilogram is 2.2 pounds) 4 | */ 5 | 6 | public class Exercise_05_03{ 7 | public static void main(String[] args){ 8 | System.out.printf("%-12s %10s%n", "Kilograms", "Pounds"); 9 | for (int i = 1; i < 200; i += 2){ 10 | System.out.printf("%-12d %10.1f%n", i, i * 2.2); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Chp5/Exercise_05_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Conversion from kilograms to pounds and pounds to kilograms Write a 3 | program that displays the following two tables side by side 4 | */ 5 | 6 | public class Exercise_05_05{ 7 | public static void main(String[] args){ 8 | System.out.printf("%-10s %8s | %-8s %10s%n", 9 | "Kilograms", 10 | "Pounds", 11 | "Pounds", 12 | "Kilograms"); 13 | 14 | int pounds = 20; 15 | for (int i = 1; i < 200; i += 2){ 16 | System.out.printf("%-10d %8.1f | %-8d %10.2f%n", 17 | i, 18 | i * 2.2, 19 | pounds, 20 | pounds * 0.4545); 21 | pounds += 5; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chp5/Exercise_05_07.java: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose that the tuition for a university 3 | is $10,000 this year and increases 5% every year. In one year, the tuition 4 | will be $10,500. Write a program that computes the tuition in ten years and 5 | the total cost of four years’ worth of tuition after the tenth year. 6 | */ 7 | 8 | public class Exercise_05_07{ 9 | public static void main(String[] args){ 10 | double tuition = 10000.0; 11 | double yearlyIncreasePercentage = 0.05; 12 | 13 | double tuitionInTenYears = 0.0; 14 | double fourYearsOfTuition = 0.0; 15 | 16 | for (int i = 0; i < 14; i++){ 17 | tuition += tuition * yearlyIncreasePercentage; 18 | 19 | if (i == 9) 20 | tuitionInTenYears = tuition; 21 | 22 | if (i == 10 || i == 11| i == 12 || i == 13) 23 | fourYearsOfTuition += tuition; 24 | } 25 | 26 | System.out.printf("Tuition cost after 10 years is: $%.2f%n" + 27 | "Four years of tuition after 10 years is: $%.2f%n", 28 | tuitionInTenYears, fourYearsOfTuition); 29 | } 30 | } -------------------------------------------------------------------------------- /Chp5/Exercise_05_12.java: -------------------------------------------------------------------------------- 1 | /* 2 | Use a while loop to find the smallest 3 | integer n such that n2 is greater than 12,000. 4 | */ 5 | 6 | public class Exercise_05_12{ 7 | public static void main(String[] args){ 8 | int n = 1; 9 | while(n*n <= 12000) 10 | { 11 | n += 1; 12 | } 13 | 14 | System.out.printf("%d^2 is the smallest integer greater than 12,000", n); 15 | } 16 | } -------------------------------------------------------------------------------- /Chp6/Exercise_06_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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 number: 5 | public static int getPentagonalNumber(int n) 6 | Write a test program that uses this method to display the first 100 pentagonal 7 | numbers with 10 numbers on each line. 8 | */ 9 | 10 | public class Exercise_06_01{ 11 | public static void main(String[] args){ 12 | System.out.println("The first 100 pentagonal number are:"); 13 | for (int i = 1; i < 101; i++){ 14 | System.out.printf("%7d ", getPentagonalNumber(i)); 15 | if (i % 10 == 0) 16 | System.out.println(); 17 | } 18 | } 19 | 20 | public static int getPentagonalNumber(int n){ 21 | return (n * (3 * n - 1)) / 2; 22 | } 23 | } -------------------------------------------------------------------------------- /Chp6/Exercise_06_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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 | (= 23). 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 and 10 | displays the sum of all its digits. 11 | */ 12 | import java.util.Scanner; 13 | 14 | public class Exercise_06_02{ 15 | public static void main(String[] args){ 16 | Scanner in = new Scanner(System.in); 17 | System.out.print("Please enter an integer to sum the digits of: "); 18 | long value = in.nextLong(); 19 | System.out.println("The sum of all digits is: " + sumDigits(value)); 20 | } 21 | 22 | public static int sumDigits(long n){ 23 | int temp = (int)Math.abs(n); 24 | int sum = 0; 25 | 26 | while(temp != 0){ 27 | sum += (temp % 10); 28 | temp = temp / 10; 29 | } 30 | 31 | return sum; 32 | } 33 | } -------------------------------------------------------------------------------- /Chp6/Exercise_06_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write the methods with the following headers 3 | // Return the reversal of an integer, i.e., 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 | 12 | import java.util.Scanner; 13 | 14 | public class Exercise_06_03 { 15 | public static void main(String[] args){ 16 | Scanner in = new Scanner(System.in); 17 | 18 | System.out.print("Please enter an integer to reverse: "); 19 | int number = in.nextInt(); 20 | 21 | System.out.printf("%d reversed is %d%n", number, reverse(number)); 22 | System.out.printf("%d is %s palindrone%n", 23 | number, 24 | isPalindrone(number) ? "a" : "not a"); 25 | } 26 | 27 | public static int reverse(int number){ 28 | String reversedNumber = ""; 29 | 30 | while(number != 0){ 31 | reversedNumber += number % 10; 32 | number = number / 10; 33 | } 34 | 35 | return Integer.parseInt(reversedNumber); 36 | } 37 | 38 | public static boolean isPalindrone(int number){ 39 | if (number == reverse(number)) 40 | return true; 41 | return false; 42 | } 43 | } -------------------------------------------------------------------------------- /Chp6/Exercise_06_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method with the following header to display three 3 | numbers in increasing 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 increasing order. 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise_06_05 { 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | System.out.print("Please enter 3 numbers seperated by a space(1 2 3): "); 17 | double num1 = in.nextDouble(); 18 | double num2 = in.nextDouble(); 19 | double num3 = in.nextDouble(); 20 | 21 | displaySortedNumbers(num1, num2, num3); 22 | } 23 | 24 | public static void displaySortedNumbers(double num1, double num2, double num3) { 25 | if (num1 > num2) { 26 | double temp = num1; 27 | num1 = num2; 28 | num2 = temp; 29 | } 30 | 31 | if (num2 > num3) { 32 | double temp = num2; 33 | num2 = num3; 34 | num3 = temp; 35 | } 36 | 37 | if (num1 > num2) { 38 | double temp = num1; 39 | num1 = num2; 40 | num2 = temp; 41 | } 42 | 43 | System.out.printf("The number in increasing order are: %f, %f, %f%n", num1, num2, num3); 44 | } 45 | } -------------------------------------------------------------------------------- /Chp7/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | worst case needs only log2(n+1) comparisons 3 | */ 4 | 5 | public class BinarySearch { 6 | // Binary search example 7 | public static int binarySearch(int[] list, int key) { 8 | int low = 0; 9 | int high = list.length - 1; 10 | 11 | while (high >= low) 12 | { 13 | int mid = (low + high) / 2; 14 | if (key < list[mid]) 15 | high = mid - 1; 16 | else if (key == list[mid]) 17 | return mid; 18 | else 19 | low = mid + 1; 20 | } 21 | return -low - 1; 22 | } 23 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads student scores, gets the best score, 3 | and then assigns grades based on the following scheme: 4 | Grade is A if score is >= best - 10 5 | Grade is B if score is >= best - 20; 6 | Grade is C if score is >= best - 30; 7 | Grade is D if score is >= best - 40; 8 | Grade is F otherwise. 9 | The program prompts the user to enter the total number of students, then prompts 10 | the user to enter all of the scores, and concludes by displaying the grades. 11 | 12 | */ 13 | 14 | import java.util.Scanner; 15 | 16 | public class Exercise_07_01 { 17 | public static void main(String[] args) { 18 | Scanner in = new Scanner(System.in); 19 | 20 | System.out.print("Enter the number of students: "); 21 | int numberOfStudents = in.nextInt(); 22 | int[] scores = new int[4]; 23 | 24 | System.out.print("Enter " + numberOfStudents + " scores: "); 25 | scores[0] = in.nextInt(); 26 | scores[1] = in.nextInt(); 27 | scores[2] = in.nextInt(); 28 | scores[3] = in.nextInt(); 29 | 30 | displayGrades(scores); 31 | } 32 | 33 | public static void displayGrades(int[] grades) { 34 | int highScore = bestGrade(grades); 35 | 36 | for (int i = 0; i < grades.length; i++) { 37 | System.out.printf("Student %d score is %d and grade is %s%n", 38 | i, grades[i], assignLetterGrade(grades[i], highScore)); 39 | } 40 | } 41 | 42 | public static char assignLetterGrade(int grade, int highScore) { 43 | 44 | if (highScore - grade <= 10) 45 | return 'A'; 46 | else if (highScore - grade > 10 && highScore - grade <= 20) 47 | return 'B'; 48 | else if (highScore - grade > 20 && highScore - grade <= 30) 49 | return 'C'; 50 | else if (highScore - grade > 30 && highScore - grade <= 20) 51 | return 'D'; 52 | else 53 | return 'F'; 54 | } 55 | 56 | public static int bestGrade(int[] grades) { 57 | int highScore = grades[0]; 58 | 59 | for (int grade : grades) { 60 | if (grade > highScore) 61 | highScore = grade; 62 | } 63 | 64 | return highScore; 65 | } 66 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads ten integers and displays 3 | them in the reverse of the order in which they were read. 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | public class Exercise_07_02 { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | int[] values = new int[10]; 13 | 14 | System.out.print("Enter 10 integer values: "); 15 | 16 | for (int i = 0; i < values.length; i++) { 17 | values[i] = in.nextInt(); 18 | } 19 | 20 | System.out.println("Values in reverse order."); 21 | for (int i = values.length - 1; i >= 0; i--) { 22 | System.out.printf("%d ", values[i]); 23 | } 24 | System.out.println(); 25 | } 26 | 27 | 28 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads the integers between 1 3 | and 100 and counts the occurrences of each. Assume the input ends with 0. 4 | Note that if a number occurs more than one time, the plural word "times" 5 | is used in the output. 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Exercise_07_03 { 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | 14 | int[] values = new int[100]; 15 | int input; 16 | int count = 0; 17 | System.out.print("Enter the integers between 1 and 100: "); 18 | do 19 | { 20 | input = in.nextInt(); 21 | values[count] = input; 22 | count += 1; 23 | } 24 | while (input != 0); 25 | 26 | countOccurence(values); 27 | } 28 | 29 | public static void countOccurence(int[] list) { 30 | for (int i = 1; i <= 100; i++) { 31 | int count = 0; 32 | for (int j = 0; j < list.length - 1; j++) { 33 | if (list[j] == i) 34 | count += 1; 35 | } 36 | if (count != 0) 37 | System.out.printf("%d occurs %d %s%n", 38 | i, count, count > 1 ? "times" : "time"); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads in ten numbers and displays 3 | the number of distinct numbers and the distinct numbers separated by exactly one 4 | space (i.e., if a number appears multiple times, it is displayed only once). (Hint: 5 | Read a number and store it to an array if it is new. If the number is already in the 6 | array, ignore it.) After the input, the array contains the distinct numbers. 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise_07_05 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int[] userValues = new int[10]; 15 | 16 | System.out.print("Enter ten numbers: "); 17 | int elementIndex = 0; 18 | 19 | // Ugly solution, but it works... 20 | 21 | for (int i = 0; i < 10; i++) { 22 | boolean inArray = false; 23 | int val = in.nextInt(); 24 | for (int j = 0; j < 10; j++) { 25 | if (val == userValues[j]) 26 | inArray = true; 27 | } 28 | if (!inArray) { 29 | userValues[elementIndex] = val; 30 | elementIndex += 1; 31 | } 32 | } 33 | System.out.printf("The number of distinct numbers is %d.%n", elementIndex); 34 | for (int a = 0; a <= elementIndex - 1; a++) { 35 | System.out.printf("%d ", userValues[a]); 36 | } 37 | System.out.println(); 38 | 39 | 40 | } 41 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_07.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that generates 100 random integers between 3 | 0 and 9 and displays the count for each number. 4 | */ 5 | 6 | public class Exercise_07_07 { 7 | public static void main(String[] args) { 8 | int[] randomInts = new int[100]; 9 | int[] count = new int[10]; 10 | 11 | // generate an array with 100 random integers between 0-9 12 | for (int i = 0; i < randomInts.length; i++) { 13 | randomInts[i] = (int)(Math.random() * 10); 14 | } 15 | // counts the occurence or each int 16 | for (int num : randomInts) { 17 | addToCount(num, count); 18 | } 19 | // displays the muber of times each integer occured 20 | System.out.println("Counts:"); 21 | for (int j = 0; j < count.length; j++) { 22 | System.out.printf("%d : %d%n", j, count[j]); 23 | } 24 | } 25 | 26 | public static void addToCount(int num, int[] count) { 27 | /* 28 | When passed an integer 0-9, adds 1 to the count for that 29 | integer in the count array. 30 | */ 31 | 32 | switch (num) 33 | { 34 | case 0: 35 | count[0] += 1; 36 | break; 37 | case 1: 38 | count[1] += 1; 39 | break; 40 | case 2: 41 | count[2] += 1; 42 | break; 43 | case 3: 44 | count[3] += 1; 45 | break; 46 | case 4: 47 | count[4] += 1; 48 | break; 49 | case 5: 50 | count[5] += 1; 51 | break; 52 | case 6: 53 | count[6] += 1; 54 | break; 55 | case 7: 56 | count[7] += 1; 57 | break; 58 | case 8: 59 | count[8] += 1; 60 | break; 61 | case 9: 62 | count[9] += 1; 63 | break; 64 | default: 65 | break; 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_08.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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 ten double values, invokes this 7 | method, and displays the average value. 8 | */ 9 | 10 | public class Exercise_07_08 { 11 | public static void main(String[] args) { 12 | java.util.Scanner in = new java.util.Scanner(System.in); 13 | double[] vals = new double[10]; 14 | System.out.print("Please enter to double values: "); 15 | 16 | for (int i = 0; i < 10; i++) 17 | vals[i] = in.nextDouble(); 18 | 19 | System.out.printf("The average is: %.2f", average(vals)); 20 | } 21 | 22 | public static int average(int[] array) { 23 | int sum = 0; 24 | for (int val : array) 25 | sum += val; 26 | return sum / array.length; 27 | } 28 | 29 | public static double average(double[] array) { 30 | double sum = 0.0; 31 | for (double val : array) 32 | sum += val; 33 | return sum / array.length; 34 | } 35 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_09.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method that finds the smallest element in an 3 | array of double values using the following header: 4 | public static double min(double[] array) 5 | Write a test program that prompts the user to enter ten numbers, invokes this 6 | method to return the minimum value, and displays the minimum value. 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise_07_09 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | double[] vals = new double[10]; 15 | System.out.print("Enter 10 number: "); 16 | 17 | for (int i = 0; i < vals.length; i++) { 18 | vals[i] = in.nextDouble(); 19 | } 20 | 21 | System.out.printf("The minimum number is: %.2f",min(vals)); 22 | } 23 | 24 | public static double min(double[] array) { 25 | double min = array[0]; 26 | for (double val : array) { 27 | if (val < min) 28 | min = val; 29 | } 30 | return min; 31 | } 32 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_10.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method that returns the index of 3 | the smallest element in an array of integers. If the number of such elements is 4 | greater than 1, return the smallest index. Use the following header: 5 | public static int indexOfSmallestElement(double[] array) 6 | Write a test program that prompts the user to enter ten numbers, invokes this 7 | method to return the index of the smallest element, and displays the index. 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class Exercise_07_10 { 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | double[] values = new double[10]; 16 | System.out.print("Enter 10 number: "); 17 | 18 | for (int i = 0; i < values.length; i++) { 19 | values[i] = in.nextDouble(); 20 | } 21 | 22 | System.out.printf("The index of the smalles element is %d", indexOfSmallestElement(values)); 23 | 24 | } 25 | 26 | 27 | public static int indexOfSmallestElement(double[] array) { 28 | double min = array[0]; 29 | int minIndex = 0; 30 | 31 | for (int i = 0; i < array.length; i++) { 32 | if (array[i] < min) { 33 | min = array[i]; 34 | minIndex = i; 35 | } 36 | } 37 | return minIndex; 38 | } 39 | } -------------------------------------------------------------------------------- /Chp7/Exercise_07_13.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method that returns a random number between 3 | 1 and 54, excluding the numbers passed in the argument. The method header is 4 | specified as follows: 5 | public static int getRandom(int... numbers) 6 | */ 7 | 8 | public class Exercise_07_13 { 9 | public static void main(String[] args) { 10 | System.out.printf("The random number is %d%n", 11 | getRandom(3,5,7,5,4,3,23,53,6,7,44,34,23)); 12 | } 13 | 14 | public static int getRandom(int... numbers) { 15 | int randomInt; 16 | boolean inUserValues; 17 | do 18 | { 19 | inUserValues = false; 20 | randomInt = (int)(Math.random() * 54 + 1); 21 | for (int i : numbers) { 22 | if (i == randomInt) { 23 | inUserValues = true; 24 | } 25 | } 26 | } while (inUserValues); 27 | 28 | return randomInt; 29 | } 30 | } -------------------------------------------------------------------------------- /Chp7/LinearSearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | Linear search an array. 3 | */ 4 | 5 | public class LinearSearch { 6 | public static int LinearSearch(int[] list, int key) { 7 | for (int i = 0; i < list.length; i++) { 8 | if (key == list[i]) 9 | return i 10 | } 11 | return -2; 12 | } 13 | } -------------------------------------------------------------------------------- /Chp7/SelectionSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | Selection sort 3 | */ 4 | 5 | public class SelectionSort { 6 | public static void selectionSort(double[] list) { 7 | for (int i = 0; i < list.length; i++) { 8 | double currentMin = list[i]; 9 | int currentMinIndex = i; 10 | 11 | for (int j = i + 1; j < list.length; j++) { 12 | if (currentMin > list[j]) { 13 | currentMin = list[j]; 14 | currentMinIndex = j; 15 | } 16 | } 17 | 18 | if (currentMinIndex != i) { 19 | list[currentMinIndex] = list[i]; 20 | list[i] = currentMin; 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chp8/Exercise_08_01.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Write a method that returns the sum of all the elements in a specified column 4 | in a matrix using the following header: 5 | public static double sumColumn(double[][] m, int columnIndex) 6 | Write a test program that reads a 3-by-4 matrix and displays the sum of 7 | each column 8 | */ 9 | import java.util.Scanner; 10 | 11 | public class Exercise_08_01 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | 15 | double[][] m = new double[3][4]; 16 | 17 | System.out.println("Enter " + m.length + "-by-" + m[0].length + " matrix row by row: "); 18 | for (int i = 0; i < m.length; i++) { 19 | for (int j = 0; j < m[0].length; j++) { 20 | m[i][j] = in.nextDouble(); 21 | } 22 | } 23 | 24 | for (int j = 0; j < m[0].length; j++) { 25 | System.out.printf("Sum of the elements at column %d is %.1f%n", j, sumColumn(m, j)); 26 | } 27 | } 28 | 29 | public static double sumColumn(double[][] m, int columnIndex) { 30 | double sum = 0.0; 31 | for (int i = 0; i < m.length; i++) { 32 | sum += m[i][columnIndex]; 33 | } 34 | return sum; 35 | } 36 | } -------------------------------------------------------------------------------- /Chp8/Exercise_08_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method that sums all the numbers in the major diagonal in an n*n 3 | matrix of double values using the following header: 4 | public static double sumMajorDiagonal(double[][] m) 5 | Write a test program that reads a 4-by-4 matrix and displays the sum of all its 6 | elements on the major diagonal. 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class Exercise_08_02 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | double[][] m = new double[4][4]; 15 | System.out.println("Enter a 4-by-4 matrix row by row: "); 16 | 17 | for (int i = 0; i < m.length; i++) { 18 | for (int j = 0; j < m[0].length; j++) { 19 | m[i][j] = in.nextDouble(); 20 | } 21 | } 22 | 23 | System.out.printf("Sum of the slements in the major diagonal is %.1f", 24 | sumMajorDiagonal(m)); 25 | 26 | } 27 | 28 | public static double sumMajorDiagonal(double[][] m) { 29 | double sum = 0.0; 30 | for (int i = 0; i < m.length; i++) { 31 | sum += m[i][i]; 32 | } 33 | return sum; 34 | } 35 | } -------------------------------------------------------------------------------- /Chp8/Exercise_08_04.java: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose the weekly hours for all employees are stored in a two-dimensional array. 3 | Each row records an employ-ee’s seven-day work hours with seven columns. 4 | For example, the following array stores the work hours for eight employees. 5 | Write a program that displays employees and their total hours in decreasing 6 | order of the total hours 7 | */ 8 | 9 | public class Exercise_08_03 { 10 | public static void main(String[] args) { 11 | int[][] employeeHours = 12 | {{2 ,4, 3, 4, 5, 8, 8}, 13 | {7, 3, 4, 3, 3, 4, 4}, 14 | {3, 3, 4, 3, 3, 2, 2}, 15 | {9, 3, 4, 7, 3, 4, 1}, 16 | {3, 5, 4, 3, 6, 3, 8}, 17 | {3, 4, 4, 6, 3, 4, 4}, 18 | {3, 7, 4, 8, 3, 8, 4}, 19 | {6, 3, 5, 9, 2, 7, 9}}; 20 | 21 | //int[][] totalHoursPerEmployee = new int[7][1]; 22 | int[] totalHoursPerEmployee = sumEmployeeHours(employeeHours); 23 | int[] indexList = new int[totalHoursPerEmployee.length]; 24 | sortWhileKeepingIndices(totalHoursPerEmployee, indexList); 25 | 26 | for (int i = 0; i < totalHoursPerEmployee.length; i++) { 27 | System.out.printf("Employee %s worked %d hours%n", indexList[i], totalHoursPerEmployee[i]); 28 | } 29 | 30 | System.out.println(java.util.Arrays.toString(indexList)); 31 | 32 | } 33 | 34 | public static int[] sumEmployeeHours(int[][] hours) { 35 | int[] totalHoursPerEmployee = new int[hours.length]; 36 | for (int i = 0; i < hours.length; i++) { 37 | int sum = 0; 38 | for (int j = 0; j < hours[i].length; j++) { 39 | sum += hours[i][j]; 40 | } 41 | totalHoursPerEmployee[i] = sum; 42 | } 43 | return totalHoursPerEmployee; 44 | } 45 | 46 | static void sortWhileKeepingIndices(int[] totalHours, int[] indexList) { 47 | //fill indexList 48 | for (int i = 0; i < indexList.length; i++) { 49 | indexList[i] = i; 50 | } 51 | 52 | for (int i = 0; i < totalHours.length; i++) { 53 | int currentMax = totalHours[i]; 54 | int currentMaxIndex = i; 55 | 56 | for (int j = i + 1; j < totalHours.length; j++) { 57 | if (currentMax < totalHours[j]) { 58 | currentMax = totalHours[j]; 59 | currentMaxIndex = j; 60 | } 61 | } 62 | 63 | if (currentMaxIndex != i) { 64 | totalHours[currentMaxIndex] = totalHours[i]; 65 | totalHours[i] = currentMax; 66 | 67 | int temp = indexList[currentMaxIndex]; 68 | indexList[currentMaxIndex] = indexList[i]; 69 | indexList[i] = temp; 70 | } 71 | System.out.println(java.util.Arrays.toString(indexList) + " - " + java.util.Arrays.toString(totalHours)); 72 | } 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /Chp8/Exercise_08_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method to add two matrices. The header of 3 | the method is as follows: 4 | public static double[][] addMatrix(double[][] a, double[][] b) 5 | */ 6 | import java.util.Scanner; 7 | 8 | public class Exercise_08_05 { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | double[][] matrixOne = new double[3][3]; 12 | double[][] matrixTwo = new double[3][3]; 13 | 14 | System.out.println("Enter matrix1 (3x3): "); 15 | for (int i = 0; i < matrixOne.length; i++) { 16 | for (int j = 0; j < matrixOne[i].length; j++) { 17 | matrixOne[i][j] = in.nextDouble(); 18 | } 19 | } 20 | 21 | System.out.println("Enter matrix2 (3x3): "); 22 | for (int i = 0; i < matrixTwo.length; i++) { 23 | for (int j = 0; j < matrixTwo[i].length; j++) { 24 | matrixTwo[i][j] = in.nextDouble(); 25 | } 26 | } 27 | 28 | double[][] sum = addMatrix(matrixOne, matrixTwo); 29 | System.out.println("The matricies added are as follows: "); 30 | 31 | for (int i = 0; i < matrixOne.length; i++) { 32 | System.out.printf("%.1f %.1f %.1f %s %.1f %.1f %.1f %s %.1f %.1f %.1f%n", 33 | matrixOne[i][0], matrixOne[i][1], matrixOne[i][2], 34 | i == 1 ? "+" : " ", 35 | matrixTwo[i][0], matrixTwo[i][1], matrixTwo[i][2], 36 | i == 1 ? "=" : " ", 37 | sum[i][0], sum[i][1], sum[i][2]); 38 | } 39 | } 40 | 41 | public static double[][] addMatrix(double[][] a, double[][] b) { 42 | double[][] c = new double[a.length][a.length]; 43 | for (int i = 0; i < a.length; i++) { 44 | for (int j = 0; j < a.length; j++) { 45 | c[i][j] = a[i][j] + b[i][j]; 46 | } 47 | } 48 | return c; 49 | } 50 | } -------------------------------------------------------------------------------- /Chp8/Exercise_08_06.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method to multiply two matrices. The 3 | header of the method is: 4 | public static double[][] multiplyMatrix(double[][] a, double[][] b) 5 | Write a test program that prompts the user to enter two 3 * 3 matrices 6 | and displays their product. 7 | */ 8 | import java.util.Scanner; 9 | 10 | public class Exercise_08_06 { 11 | public static void main(String[] args) { 12 | // read in two 3x3 matrices 13 | Scanner in = new Scanner(System.in); 14 | double[][] matrixOne = new double[3][3]; 15 | double[][] matrixTwo = new double[3][3]; 16 | 17 | System.out.println("Enter matrix1 (3x3): "); 18 | for (int i = 0; i < matrixOne.length; i++) { 19 | for (int j = 0; j < matrixOne[i].length; j++) { 20 | matrixOne[i][j] = in.nextDouble(); 21 | } 22 | } 23 | 24 | System.out.println("Enter matrix2 (3x3): "); 25 | for (int i = 0; i < matrixTwo.length; i++) { 26 | for (int j = 0; j < matrixTwo[i].length; j++) { 27 | matrixTwo[i][j] = in.nextDouble(); 28 | } 29 | } 30 | 31 | double[][] sum = multiplyMatrix(matrixOne, matrixTwo); 32 | 33 | for (int i = 0; i < matrixOne.length; i++) { 34 | System.out.printf("%.1f %.1f %.1f %s %.1f %.1f %.1f %s %.1f %.1f %.1f%n", 35 | matrixOne[i][0], matrixOne[i][1], matrixOne[i][2], 36 | i == 1 ? "*" : " ", 37 | matrixTwo[i][0], matrixTwo[i][1], matrixTwo[i][2], 38 | i == 1 ? "=" : " ", 39 | sum[i][0], sum[i][1], sum[i][2]); 40 | } 41 | 42 | } 43 | 44 | public static double[][] multiplyMatrix(double[][] a, double[][] b) { 45 | double[][] c = new double[a.length][a.length]; 46 | for (int i = 0; i < a.length; i++) { 47 | for (int j = 0; j < a.length; j++) { 48 | for (int k = 0; k < a[i].length; k++) { 49 | c[i][j] += a[i][k] * b[k][j]; 50 | } 51 | } 52 | } 53 | return c; 54 | } 55 | } -------------------------------------------------------------------------------- /Chp8/Exercise_08_11.java: -------------------------------------------------------------------------------- 1 | /* 2 | Nine coins are placed in a 3-by-3 matrix with some 3 | face up and some face down. You can represent the state of the coins using a 4 | 3-by-3 matrix with values 0 (heads) and 1 (tails). 5 | Each state can also be represented using a binary number 6 | There are a total of 512 possibilities, so you can use decimal numbers 7 | 0, 1, 2, 3, ... and 511 to represent all states of the matrix. Write a program that prompts 8 | the user to enter a number between 0 and 511 and displays the corresponding 9 | matrix with the characters H and T. 10 | */ 11 | import java.util.Scanner; 12 | 13 | public class Exercise_08_11 { 14 | /* 15 | Not happy with this solution, but it works... 16 | */ 17 | public static void main(String[] args) { 18 | Scanner in = new Scanner(System.in); 19 | char[] binaryArray = new char[9]; 20 | for (int i = 0; i < binaryArray.length; i++) 21 | binaryArray[i] = '0'; 22 | 23 | System.out.print("Enter an integer between 0 and 511: "); 24 | char[] userBinaryCharArray = (Integer.toBinaryString(in.nextInt())).toCharArray(); 25 | 26 | for (int i = 0; i < userBinaryCharArray.length; i++) { 27 | binaryArray[binaryArray.length - i - 1] = userBinaryCharArray[i]; 28 | } 29 | 30 | for (int j = 0; j < binaryArray.length; j++) { 31 | if (j % 3 == 0) System.out.println(); 32 | System.out.printf("%s ", binaryArray[j] == '0' ? 'H' : 'T'); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Chp8/Exercise_08_13.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write the following method that returns the location 3 | of the largest element in a two-dimensional array. 4 | public static int[] locateLargest(double[][] a) 5 | The return value is a one-dimensional array that contains two elements. These 6 | two elements indicate the row and column indices of the largest element in the 7 | two-dimensional array. Write a test program that prompts the user to enter a twodimensional 8 | array and displays the location of the largest element in the array. 9 | */ 10 | import java.util.Scanner; 11 | 12 | public class Exercise_08_13 { 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | System.out.print("Enter the number of rows and columns in the array: "); 17 | int rows = in.nextInt(); 18 | int columns = in.nextInt(); 19 | double[][] userArray = new double[rows][columns]; 20 | System.out.println("Enter the array:"); 21 | for (int i = 0; i < userArray.length; i++) { 22 | for (int j = 0; j < userArray[i].length; j++) { 23 | userArray[i][j] = in.nextDouble(); 24 | } 25 | } 26 | 27 | int[] location = locateLargest(userArray); 28 | System.out.printf("The location of the largest element is (%d, %d)%n", 29 | location[0], location[1]); 30 | } 31 | 32 | public static int[] locateLargest(double[][] a) { 33 | int[] location = new int[]{0, 0}; 34 | double largest = a[0][0]; 35 | for (int i = 0; i < a.length; i++) { 36 | for (int j = 0; j < a[i].length; j++) { 37 | if (largest < a[i][j]) { 38 | largest = a[i][j]; 39 | location[0] = i; 40 | location[1] = j; 41 | } 42 | } 43 | } 44 | return location; 45 | } 46 | 47 | 48 | } -------------------------------------------------------------------------------- /Chp9/Exercise_09_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that creates a Date object, sets its elapsed 3 | time to 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 4 | 10000000000, and 100000000000, and displays the date and time using the 5 | toString() method, respectively 6 | */ 7 | public class Exercise_09_01 { 8 | public static void main(String[] args) { 9 | java.util.Date date = new java.util.Date(); 10 | //date.setTime(10000); 11 | long[] times = new long[] { 12 | 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 13 | 10000000000L, 100000000000L 14 | }; 15 | 16 | for (int i = 0; i < times.length; i++) { 17 | date.setTime(times[i]); 18 | System.out.println(date.toString()); 19 | } 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /Chp9/Exercise_09_04.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that creates a Random object with seed 3 | 1000 and displays the first 50 random integers between 0 and 100 using the 4 | nextInt(100) method. 5 | */ 6 | 7 | public class Exercise_09_02 { 8 | public static void main(String[] args) { 9 | java.util.Random rand = new java.util.Random(1000); 10 | 11 | for (int i = 0; i < 50; i++) { 12 | System.out.print(rand.nextInt(100) + " "); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Chp9/Exercise_09_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Java API has the GregorianCalendar class 3 | in the java.util package, which you can use to obtain the year, month, and day of a 4 | date. The no-arg constructor constructs an instance for the current date, and the methods 5 | get(GregorianCalendar.YEAR), get(GregorianCalendar.MONTH), 6 | and get(GregorianCalendar.DAY_OF_MONTH) return the year, month, and day. 7 | Write a program to perform two tasks: 8 | Display the current year, month, and day. 9 | The GregorianCalendar class has the setTimeInMillis(long), which 10 | can be used to set a specified elapsed time since January 1, 1970. Set the value 11 | to 1234567898765L and display the year, month, and day. 12 | */ 13 | import java.util.*; 14 | 15 | public class Exercise_09_05 { 16 | public static void main(String[] args) { 17 | GregorianCalendar c = new GregorianCalendar(); 18 | System.out.printf("Today is %d/%d/%d%n", 19 | c.get(GregorianCalendar.MONTH) + 1, 20 | c.get(GregorianCalendar.DAY_OF_MONTH), 21 | c.get(GregorianCalendar.YEAR)); 22 | 23 | c.setTimeInMillis(1234567898765L); 24 | System.out.printf("After setting time: %d/%d/%d", 25 | c.get(GregorianCalendar.MONTH) + 1, 26 | c.get(GregorianCalendar.DAY_OF_MONTH), 27 | c.get(GregorianCalendar.YEAR)); 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /Chp9/Exercise_09_06_Test.java: -------------------------------------------------------------------------------- 1 | /* 2 | Design a class named StopWatch. The class contains: 3 | Private data fields startTime and endTime with getter methods. 4 | A no-arg constructor that initializes startTime with the current time. 5 | A method named start() that resets the startTime to the current time. 6 | A method named stop() that sets the endTime to the current time. 7 | A method named getElapsedTime() that returns the elapsed time for the 8 | stopwatch in milliseconds. 9 | 10 | Write a test 11 | program that measures the execution time of sorting 100,000 numbers using 12 | selection sort 13 | */ 14 | public class Exercise_09_06_Test { 15 | public static void main(String[] args) { 16 | java.util.Random r = new java.util.Random(); 17 | int[] numbers = new int[100000]; 18 | 19 | for(int i = 0; i < numbers.length; i++) { 20 | numbers[i] = r.nextInt(10000); 21 | } 22 | 23 | StopWatch stopWatch = new StopWatch(); 24 | selectionSort(numbers); 25 | stopWatch.stop(); 26 | 27 | System.out.println("Sorting 100,000 numbers took " + stopWatch.getElapsedTime() + " milliseconds"); 28 | } 29 | 30 | public static void selectionSort(int[] list) { 31 | for (int i = 0; i < list.length; i++) { 32 | int currentMin = list[i]; 33 | int currentMinIndex = i; 34 | 35 | for (int j = i + 1; j < list.length; j++) { 36 | if (currentMin > list[j]) { 37 | currentMin = list[j]; 38 | currentMinIndex = j; 39 | } 40 | } 41 | 42 | if (currentMinIndex != i) { 43 | list[currentMinIndex] = list[i]; 44 | list[i] = currentMin; 45 | } 46 | } 47 | } 48 | } 49 | 50 | 51 | class StopWatch { 52 | private long startTime = System.currentTimeMillis(); 53 | private long endTime = startTime; 54 | 55 | 56 | public StopWatch() { 57 | } 58 | 59 | public long getStartTime() { 60 | return this.startTime; 61 | } 62 | 63 | public long getEndTime() { 64 | return this.endTime; 65 | } 66 | 67 | public void start() { 68 | this.startTime = System.currentTimeMillis(); 69 | } 70 | 71 | public void stop() { 72 | this.endTime = System.currentTimeMillis(); 73 | } 74 | 75 | public long getElapsedTime() { 76 | return this.endTime - this.startTime; 77 | } 78 | } -------------------------------------------------------------------------------- /Chp9/Exercise_09_07.java: -------------------------------------------------------------------------------- 1 | /* 2 | Design a class named Account that contains: 3 | A private int data field named id for the account (default 0). 4 | A private double data field named balance for the account (default 0). 5 | A private double data field named annualInterestRate that stores the current 6 | interest rate (default 0). Assume all accounts have the same interest rate. 7 | A private Date data field named dateCreated that stores the date when the 8 | account was created. 9 | A no-arg constructor that creates a default account. 10 | A constructor that creates an account with the specified id and initial balance. 11 | The accessor and mutator methods for id, balance, and annualInterestRate. 12 | The accessor method for dateCreated. 13 | A method named getMonthlyInterestRate() that returns the monthly 14 | interest rate. 15 | A method named getMonthlyInterest() that returns the monthly interest. 16 | A method named withdraw that withdraws a specified amount from the 17 | account. 18 | A method named deposit that deposits a specified amount to the account. 19 | 20 | Write a test program that creates an Account object with an account ID of 1122, 21 | a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw 22 | method to withdraw $2,500, use the deposit method to deposit $3,000, and print 23 | the balance, the monthly interest, and the date when this account was created 24 | */ 25 | 26 | public class Exercise_09_07 { 27 | public static void main(String[] args) { 28 | Account account = new Account(1122, 20000); 29 | account.setAnnualInterestRate(4.5); 30 | account.withdraw(2500.0); 31 | account.deposit(3000.0); 32 | System.out.println("Balance: $" + account.getBalance()); 33 | System.out.println("Monthly Interest: " + account.getMonthlyInterest()); 34 | System.out.println("Date Created: " + account.getDateCreated()); 35 | 36 | } 37 | } 38 | 39 | class Account { 40 | private int id = 0; 41 | private double balance = 0.0; 42 | private static double annualInterestRate = 0.0; 43 | private java.util.Date dateCreated; 44 | 45 | public Account() { 46 | dateCreated = new java.util.Date(); 47 | } 48 | 49 | public Account(int id, double balace) { 50 | this(); 51 | this.id = id; 52 | this.balance = balance; 53 | } 54 | 55 | public int getId() { 56 | return this.id; 57 | } 58 | 59 | public double getBalance() { 60 | return this.balance; 61 | } 62 | 63 | public double getAnnualInterestRate() { 64 | return annualInterestRate; 65 | } 66 | 67 | public String getDateCreated() { 68 | return this.dateCreated.toString(); 69 | } 70 | 71 | public void setId(int id) { 72 | this.id = id; 73 | } 74 | 75 | public void setBalance(double balance) { 76 | this.balance = balance; 77 | } 78 | 79 | public void setAnnualInterestRate(double annualInterestRate) { 80 | this.annualInterestRate = annualInterestRate; 81 | } 82 | 83 | public double getMonthlyInterestRate() { 84 | return (annualInterestRate / 100) / 12 ; 85 | } 86 | 87 | public double getMonthlyInterest() { 88 | return balance * getMonthlyInterestRate(); 89 | } 90 | 91 | public void withdraw(double amount) { 92 | this.balance -= amount; 93 | } 94 | 95 | public void deposit(double amount) { 96 | this.balance += amount; 97 | } 98 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Intro-To-Java-Programming 2 | Solution to Intro to Java Programming 10th ed. by Y. Daniel Liang 3 | --------------------------------------------------------------------------------