├── Chapter02 ├── Examples │ ├── 2.01 │ │ └── Welcome1.java │ ├── 2.03 │ │ └── Welcome2.java │ ├── 2.04 │ │ └── Welcome3.java │ ├── 2.06 │ │ └── Welcome4.java │ ├── 2.07 │ │ └── Addition.java │ ├── 2.15 │ │ └── Comparison.java │ └── README.md └── Exercises │ ├── 2.06 │ └── Product.java │ ├── 2.14 │ └── NumberSpace.java │ ├── 2.15 │ └── Arithmetic.java │ ├── 2.16 │ └── ComparingIntegers.java │ ├── 2.17 │ └── Calculations.java │ ├── 2.18 │ └── Asterisk1.java │ ├── 2.19 │ └── Asterisk2.java │ ├── 2.20 │ └── Asterisk3.java │ ├── 2.21 │ └── Asterisk4.java │ ├── 2.22 │ └── Asterisk.java │ ├── 2.23 │ └── Asterisk6.java │ ├── 2.24 │ └── FiveIntegers.java │ ├── 2.25 │ └── OddEven.java │ ├── 2.26 │ └── Multiple.java │ ├── 2.27 │ └── Asterisk.java │ ├── 2.28 │ └── Circle.java │ ├── 2.29 │ └── IntegerValue.java │ ├── 2.30 │ └── SeparateDigit.java │ ├── 2.31 │ └── SquareCube.java │ ├── 2.32 │ └── NegativePositiveZero.java │ ├── 2.33 │ └── BMI.java │ ├── 2.34 │ └── WorldPopulation.java │ ├── 2.35 │ └── DrivingCost.java │ └── README.md ├── Chapter03 ├── Examples │ ├── 3.06 │ │ └── ClassAverage.java │ ├── 3.08 │ │ └── ClassAverage.java │ ├── 3.10 │ │ └── Analysis.java │ └── 3.13 │ │ └── Increment.java └── Exercises │ ├── 3.06 │ └── Calculate.java │ ├── 3.16 │ └── Mystery.java │ ├── 3.17 │ └── GasMileage.java │ ├── 3.18 │ └── CreditLimit.java │ ├── 3.19 │ └── SalesCommission.java │ ├── 3.20 │ └── Salary.java │ ├── 3.21 │ └── Largest.java │ ├── 3.22 │ └── Table10.java │ ├── 3.23 │ └── TwoLargest.java │ ├── 3.24 │ └── AnalysisMod.java │ ├── 3.25 │ └── Mystery2.java │ ├── 3.26 │ └── Mystery3.java │ ├── 3.27 │ └── DanglingElse.java │ ├── 3.28 │ └── DanglingElse2.java │ ├── 3.29 │ └── AsteriskSquare.java │ ├── 3.30 │ └── Palindrome.java │ ├── 3.31 │ └── BinarytoDecimal.java │ ├── 3.32 │ └── AsteriskChecker.java │ ├── 3.33 │ └── InfiniteTwo.java │ ├── 3.34 │ └── IncrementError.java │ ├── 3.35 │ └── Triangle.java │ ├── 3.36 │ └── RightTriangle.java │ ├── 3.37a │ └── Factorial.java │ ├── 3.37b │ └── Factoriale.java │ ├── 3.37c │ └── FactorialEx.java │ ├── 3.38 │ └── Encryption.java │ └── 3.39 │ └── GlobalPopulation.java ├── Chapter04 ├── Examples │ ├── 4.01 │ │ └── WhileCounter.java │ ├── 4.02 │ │ └── ForCounter.java │ ├── 4.05 │ │ └── Sum.java │ ├── 4.06 │ │ └── Interest.java │ ├── 4.07 │ │ └── DoWhileTest.java │ ├── 4.09 │ │ └── LetterGrades.java │ ├── 4.11 │ │ └── BreakTest.java │ ├── 4.12 │ │ └── ContinueTest.java │ └── 4.17 │ │ └── LogicalOperators.java └── Exercises │ ├── 4.10 │ └── Printing.java │ ├── 4.11 │ └── SmallestValue.java │ ├── 4.12 │ └── Product.java │ ├── 4.13 │ └── Factorial.java │ ├── 4.14 │ └── Interest.java │ ├── 4.15 │ └── Asterisk.java │ ├── 4.16 │ └── BarGraph.java │ ├── 4.17 │ └── Sales.java │ ├── 4.18 │ └── Interest.java │ ├── 4.19 │ └── Mystery.java │ ├── 4.20 │ └── PI.java │ ├── 4.21 │ └── PythagoreanTriples.java │ ├── 4.22 │ └── Asterisk2.java │ ├── 4.23 │ └── DeMorgan.java │ ├── 4.24 │ └── Asterisk3.java │ ├── 4.25 │ └── Asterisk4.java │ ├── 4.26 │ └── BreakSubstitute.java │ ├── 4.27 │ └── Mystery2.java │ ├── 4.28 │ └── ContinueSubstitute.java │ ├── 4.29 │ └── TwelveDays.java │ ├── 4.30 │ └── GlobalWarming.java │ ├── 4.31 │ └── FairTax.java │ └── 4.32 │ └── Facebook.java ├── Chapter05 ├── Examples │ ├── 5.03 │ │ └── MaximumFinder.java │ ├── 5.06 │ │ └── RandomIntegers.java │ ├── 5.07 │ │ └── RollDie.java │ ├── 5.08 │ │ └── Craps.java │ ├── 5.09 │ │ └── Scope.java │ └── 5.10 │ │ └── MethodOverload.java └── Exercises │ ├── 5.03 │ └── MathTest.java │ ├── 5.06 │ └── Sphere.java │ ├── 5.08 │ └── ParkingCharge.java │ ├── 5.09 │ └── Rounding.java │ ├── 5.10 │ └── Rounding2.java │ ├── 5.12 │ └── RandomInteger.java │ ├── 5.13 │ └── RandomInteger2.java │ ├── 5.14 │ └── Exponentiation.java │ ├── 5.15 │ └── Hypotenuse.java │ ├── 5.16 │ └── Multiples.java │ ├── 5.17 │ └── EvenOdd.java │ ├── 5.18 │ └── Asterisk.java │ ├── 5.19 │ └── CharacterSquare.java │ ├── 5.20 │ └── CircleArea.java │ ├── 5.21 │ └── SeparateDigits.java │ ├── 5.22 │ └── Temperature.java │ ├── 5.23 │ └── Minimum.java │ ├── 5.24 │ └── PerfectNumbers.java │ ├── 5.25 │ └── Prime.java │ ├── 5.26 │ └── ReverseDigits.java │ ├── 5.27 │ └── GreatestCommonFactor.java │ ├── 5.28 │ └── GradeAverage.java │ ├── 5.29 │ └── HeadTails.java │ ├── 5.30 │ └── GuessNumber.java │ ├── 5.31 │ └── GuessNumberMod.java │ ├── 5.32 │ └── Distance.java │ ├── 5.33 │ └── CrapsMod.java │ ├── 5.34 │ └── DecimalConversion.java │ ├── 5.35 │ └── CAI.java │ ├── 5.36 │ └── CAI2.java │ ├── 5.37 │ └── CAI3.java │ ├── 5.38 │ └── CAI4.java │ └── 5.39 │ └── CAI5.java ├── Chapter06 ├── Examples │ ├── 6.02 │ │ └── InitArray.java │ ├── 6.03 │ │ └── InitArray.java │ ├── 6.04 │ │ └── InitArray.java │ ├── 6.05 │ │ └── SumArray.java │ ├── 6.06 │ │ └── BarChart.java │ ├── 6.07 │ │ └── RollDie.java │ ├── 6.09 │ │ └── EnhancedForTest.java │ ├── 6.10 │ │ └── PassArray.java │ ├── 6.12 │ │ └── InitArray.java │ ├── 6.13 │ │ └── VarargsTest.java │ ├── 6.14 │ │ └── InitArray.java │ ├── 6.15 │ │ └── ArrayManipulations.java │ └── 6.17 │ │ └── ArrayListCollection.java └── Exercises │ ├── 6.10 │ └── SalesCommission.java │ ├── 6.12 │ └── DuplicateElimination.java │ ├── 6.14 │ └── VariableProduct.java │ ├── 6.15 │ └── CommandLine.java │ ├── 6.16 │ └── EnhancedFor.java │ ├── 6.17 │ └── DiceSum.java │ ├── 6.18 │ └── CrapsArray.java │ ├── 6.19 │ └── Reservations.java │ ├── 6.21 │ └── Turtle.java │ ├── 6.27 │ └── Sieveoferatosthenes.java │ ├── 6.28 │ └── TortoiseHare.java │ └── 6.29 │ └── Fibonacci.java ├── Chapter07 ├── Examples │ ├── 7.01 │ │ └── Account.java │ ├── 7.02 │ │ └── AccountTest.java │ ├── 7.05 │ │ └── Account.java │ ├── 7.06 │ │ └── AccountTest.java │ ├── 7.08 │ │ └── Account.java │ ├── 7.09 │ │ └── AccountTest.java │ ├── 7.11 │ │ └── Card.java │ ├── 7.12 │ │ └── DeckOfCards.java │ ├── 7.13 │ │ └── DeckOfCardsTest.java │ ├── 7.14 │ │ └── GradeBook.java │ ├── 7.15 │ │ └── GradeBookTest.java │ ├── 7.16 │ │ └── GradeBook.java │ └── 7.17 │ │ └── GradeBookTest.java └── Exercises │ ├── 7.10 │ ├── Account.java │ └── AccountTest.java │ ├── 7.11 │ ├── Invoice.java │ └── InvoiceTest.java │ ├── 7.12 │ ├── Employee.java │ └── EmployeeTest.java │ ├── 7.13 │ ├── Date.java │ └── DateTest.java │ ├── 7.14 │ ├── Account.java │ └── AccountTest.java │ └── 7.15 │ ├── GradeBook.java │ └── GradeBookTest.java ├── Chapter08 ├── Examples │ ├── 8.01 │ │ └── Time1.java │ ├── 8.02 │ │ └── Time1Test.java │ ├── 8.03 │ │ └── MemberAccessTest.java │ ├── 8.04 │ │ └── ThisTest.java │ ├── 8.05 │ │ └── Time2.java │ ├── 8.06 │ │ └── Time2Test.java │ ├── 8.07 │ │ └── Date.java │ ├── 8.08 │ │ └── Employee.java │ ├── 8.09 │ │ └── EmployeeTest.java │ ├── 8.10 │ │ └── Book.java │ ├── 8.11 │ │ └── EnumTest.java │ ├── 8.12 │ │ └── Employee.java │ ├── 8.13 │ │ └── EmployeeTest.java │ ├── 8.14 │ │ └── StaticImportTest.java │ ├── 8.15 │ │ └── PackageDataTest.java │ └── 8.16 │ │ └── Interest.java └── Exercises │ ├── 8.04 │ ├── Rectangle.java │ └── RectangleTest.java │ ├── 8.05 │ ├── Time2Seconds.java │ └── Time2Test.java │ ├── 8.06 │ ├── SavingsAccount.java │ └── SavingsAccountTest.java │ ├── 8.07 │ ├── Time2.java │ └── Time2Test.java │ ├── 8.08 │ ├── Date.java │ └── DateTest.java │ ├── 8.09 │ └── StaticImportTest.java │ ├── 8.10 │ ├── EnumTest.java │ └── TrafficLight.java │ ├── 8.11 │ ├── Complex.java │ └── ComplexTest.java │ ├── 8.12 │ ├── DateAndTime.java │ └── DateAndTimeTest.java │ ├── 8.13 │ ├── IntegerSet.java │ └── IntegerSetTest.java │ ├── 8.14 │ ├── Date.java │ └── DateTest.java │ └── 8.15 │ ├── Rational.java │ └── RationalTest.java ├── Chapter09 ├── Examples │ ├── 9.04 │ │ └── CommissionEmployee.java │ ├── 9.05 │ │ └── CommissionEmployeeTest.java │ ├── 9.06 │ │ └── BasePlusCommissionEmployee.java │ ├── 9.07 │ │ └── BasePlusCommissionEmployeeTest.java │ ├── 9.08 │ │ └── BasePlusCommissionEmployee.java │ ├── 9.09 │ │ └── BasePlusCommissionEmployee.java │ ├── 9.10 │ │ └── CommissionEmployee.java │ └── 9.11 │ │ └── BasePlusCommissionEmployee.java └── Exercises │ ├── 9.03 │ ├── BasePlusCommissionEmployee.java │ └── BasePlusCommissionEmployeeTest.java │ ├── 9.08 │ ├── Parallelogram.java │ ├── Point.java │ ├── Quadrilateral.java │ ├── QuadrilateralTest.java │ ├── Rectangle.java │ ├── Square.java │ └── Trapezoid.java │ ├── 9.14 │ ├── CommissionEmployee.java │ └── Employee.java │ └── 9.15 │ ├── Employee.java │ ├── HourlyEmployee.java │ └── HourlyEmployeeTest.java ├── Chapter10 ├── Examples │ ├── 10.01 │ │ └── PolymorphismTest.java │ ├── 10.04 │ │ └── Employee.java │ ├── 10.05 │ │ └── SalariedEmployee.java │ ├── 10.06 │ │ └── HourlyEmployee.java │ ├── 10.07 │ │ └── CommissionEmployee.java │ ├── 10.08 │ │ └── BasePlusCommissionEmployee.java │ ├── 10.09 │ │ └── PayrollSystemTest.java │ ├── 10.11 │ │ └── Payable.java │ ├── 10.12 │ │ └── Invoice.java │ ├── 10.13 │ │ └── Employee.java │ ├── 10.14 │ │ └── SalariedEmployee.java │ └── 10.15 │ │ └── PayableInterfaceTest.java └── Exercises │ ├── 10.12 │ ├── Date.java │ ├── Employee.java │ └── PayrollSystemTest.java │ ├── 10.13 │ ├── Circle.java │ ├── Cube.java │ ├── Shape.java │ ├── ShapeTest.java │ ├── Sphere.java │ ├── Square.java │ ├── Tetrahedron.java │ ├── ThreeDimensionalShape.java │ ├── Triangle.java │ └── TwoDimensionalShape.java │ ├── 10.14 │ └── PieceWorker.java │ ├── 10.15 │ ├── BasePlusCommissionEmployee.java │ ├── CommissionEmployee.java │ ├── HourlyEmployee.java │ └── PayableInterfaceTest.java │ └── 10.16 │ └── Employee.java ├── Chapter11 └── Examples │ ├── 11.02 │ └── DivideByZeroNoExceptionHandling.java │ ├── 11.03 │ └── DivideByZeroWithExceptionHandling.java │ ├── 11.05 │ └── UsingExceptions.java │ ├── 11.06 │ └── UsingExceptions.java │ ├── 11.07 │ └── UsingChainedExceptions.java │ └── 11.08 │ └── AssertTest.java ├── Chapter14 ├── Examples │ ├── 14.01 │ │ └── StringConstructors.java │ ├── 14.02 │ │ └── StringMiscellaneous.java │ ├── 14.03 │ │ └── StringCompare.java │ ├── 14.04 │ │ └── StringStartEnd.java │ ├── 14.05 │ │ └── StringIndexMethods.java │ ├── 14.06 │ │ └── SubString.java │ ├── 14.07 │ │ └── StringConcatenation.java │ ├── 14.08 │ │ └── StringMiscellaneous2.java │ ├── 14.09 │ │ └── StringValueOf.java │ ├── 14.10 │ │ └── StringBuilderConstructors.java │ ├── 14.11 │ │ └── StringBuilderCapLen.java │ ├── 14.12 │ │ └── StringBuilderChars.java │ ├── 14.15 │ │ └── StaticCharMethods.java │ ├── 14.16 │ │ └── StaticCharMethods2.java │ ├── 14.17 │ │ └── OtherCharMethods.java │ ├── 14.18 │ │ └── TokenTest.java │ ├── 14.20 │ │ └── ValidateInput.java │ ├── 14.21 │ │ └── Validate.java │ ├── 14.23 │ │ └── RegexSubstitution.java │ └── 14.24 │ │ └── RegexMatches.java └── Exercises │ ├── 14.03 │ └── CompareTo.java │ ├── 14.04 │ └── ComparePortions.java │ ├── 14.05 │ └── RandomSentences.java │ ├── 14.06 │ └── Limericks.java │ ├── 14.07 │ └── PigLatin.java │ ├── 14.08 │ └── PhoneNumber.java │ ├── 14.09 │ └── ReverseWords.java │ ├── 14.10 │ └── BothCases.java │ ├── 14.11 │ └── StringSearch.java │ └── 14.12 │ └── StringSearch2.java └── README.md /Chapter02/Examples/2.01/Welcome1.java: -------------------------------------------------------------------------------- 1 | // Fig. 2.1: Welcome1.java 2 | //Text-printing program 3 | 4 | public class Welcome1 { 5 | // main method begins execution of Java application 6 | public static void main(String[] args) { 7 | System.out.println("Welcome to Java Programing!"); 8 | } //end method main 9 | } // end class Welcome1 10 | -------------------------------------------------------------------------------- /Chapter02/Examples/2.03/Welcome2.java: -------------------------------------------------------------------------------- 1 | //Fig. 2.3: Welcome2.java 2 | //Printing a line of text with multiple statements 3 | 4 | public class Welcome2 { 5 | 6 | //main method begins execution of Java application 7 | public static void main(String[] args) { 8 | System.out.print("Welcome to "); 9 | System.out.println("Java Programming!"); 10 | } // end method main 11 | } // end class Welcome2 12 | -------------------------------------------------------------------------------- /Chapter02/Examples/2.04/Welcome3.java: -------------------------------------------------------------------------------- 1 | //Fig 2.4: Welcome3.java 2 | // Printing multiple lines of text with a single statement. 3 | 4 | public class Welcome3 { 5 | // main method begins execution of Java application 6 | public static void main(String[] args) { 7 | System.out.println("Welcome\nto\nJava\nProgramming!"); 8 | } // end method main 9 | } // end class Welcome3 10 | -------------------------------------------------------------------------------- /Chapter02/Examples/2.06/Welcome4.java: -------------------------------------------------------------------------------- 1 | // Fig. 2.6: Welcome4.java 2 | // Displaying multiple lines with method System.out.printf. 3 | 4 | public class Welcome4 { 5 | // main method begins execution of Java application 6 | public static void main(String[] args) { 7 | System.out.printf("%s%n%s%n", "Welcome to", "Java Programming!"); 8 | } // end method main 9 | } // end class Welcome4 10 | -------------------------------------------------------------------------------- /Chapter02/Examples/2.07/Addition.java: -------------------------------------------------------------------------------- 1 | // Fig. 2.7: Addition.java 2 | // Addition program that inputs two numbers then displays their sum. 3 | import java.util.Scanner; 4 | 5 | public class Addition { 6 | // main method begins execution of Java application 7 | public static void main(String[] args) { 8 | // create a Scanner to obtain input from the command window 9 | Scanner input = new Scanner(System.in); 10 | 11 | int number1; // first number to add 12 | int number2; // second number to add 13 | int sum; // sum of number1 and number2 14 | 15 | System.out.print("Enter first integer: "); // prompt 16 | number1 = input.nextInt(); // read first number from user 17 | 18 | System.out.print("Enter second integer: "); // prompt 19 | number2 = input.nextInt(); // read second number from user 20 | 21 | sum = number1 + number2; // add numbers, then store total in sum 22 | 23 | System.out.printf("Sum is %d%n", sum); // display sum 24 | } // end method main 25 | } // end class Addition 26 | -------------------------------------------------------------------------------- /Chapter02/Examples/README.md: -------------------------------------------------------------------------------- 1 | ## Example Guide 2 | > - [2.1](https://github.com/Hoid17/Java-How-To-Program-10E/tree/master/Chapter02/Examples/2.01) - Displays a line of text 3 | > - [2.3](https://github.com/Hoid17/Java-How-To-Program-10E/tree/master/Chapter02/Examples/2.03) - Displays a single line of code with multiple statements 4 | > - [2.4](https://github.com/Hoid17/Java-How-To-Program-10E/tree/master/Chapter02/Examples/2.04) - Displays multiple lines of text with a single statement 5 | > - [2.6](https://github.com/Hoid17/Java-How-To-Program-10E/tree/master/Chapter02/Examples/2.06) - Displays formatted text with System.out.printf 6 | > - [2.7](https://github.com/Hoid17/Java-How-To-Program-10E/tree/master/Chapter02/Examples/2.07) - Inputs two numbers and displays their sum 7 | > - [2.15](https://github.com/Hoid17/Java-How-To-Program-10E/tree/master/Chapter02/Examples/2.15) - Compares two integers six different ways 8 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.06/Product.java: -------------------------------------------------------------------------------- 1 | // Ex. 2.6: Product.java 2 | // Calculate the product of three integers 3 | package pkg2_6; 4 | import java.util.Scanner; 5 | 6 | public class Product { 7 | public static void main(String[] args) { 8 | // create Scanner to obtain input from command window 9 | Scanner input = new Scanner(System.in); 10 | 11 | int x; // first number input by user 12 | int y; // second number input by user 13 | int z; // third number input by user 14 | int result; // product of numbers 15 | 16 | System.out.print("Enter first integer: "); // prompt for input 17 | x = input.nextInt(); // read first integer 18 | 19 | System.out.print("Enter second integer: "); // prompt for input 20 | y = input.nextInt(); // read second integer 21 | 22 | System.out.print("Enter third integer: "); // prompt for input 23 | z = input.nextInt(); // read third integer 24 | 25 | result = x * y * z; // calculate product of numbers 26 | 27 | System.out.printf("The product is %d%n", result); 28 | } // end method main 29 | } // end class Product 30 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.14/NumberSpace.java: -------------------------------------------------------------------------------- 1 | // Displays the numbers 1 through 4 2 | // in three different programming methods 3 | package pkg2_14; 4 | 5 | public class NumberSpace { 6 | public static void main(String[] args) { 7 | System.out.println("1 2 3 4"); //Statement with one println statements 8 | 9 | System.out.print("1 "); // Statement with four print statements 10 | System.out.print("2 "); 11 | System.out.print("3 "); 12 | System.out.print("4 \n"); 13 | 14 | System.out.printf("%s%n", "1 2 3 4"); // Statement with one printf statement 15 | } // end method main 16 | } // end class NumberSpace 17 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.15/Arithmetic.java: -------------------------------------------------------------------------------- 1 | // Find the sum, product, difference, and quotient of two numbers given 2 | // by user 3 | // @Author: Adam Janecka 4 | package pkg2_15; 5 | import java.util.Scanner; 6 | 7 | public class Arithmetic { 8 | public static void main(String[] args) { 9 | Scanner input = new Scanner(System.in); 10 | 11 | int x; // First integer 12 | int y; // Second integer 13 | int sum; // Addition 14 | int difference; // Subtraction 15 | int product; // Multiplication 16 | int quotient; // Division 17 | 18 | System.out.print("Enter first inger: "); // Prompt 19 | x = input.nextInt(); // Get First Integer 20 | 21 | System.out.print("Enter second integer: "); // Prompt 22 | y = input.nextInt(); // Get Second Integer 23 | 24 | sum = x + y; //Declaring four operations 25 | difference = x - y; 26 | product = x * y; 27 | quotient = x / y; 28 | 29 | System.out.printf("The sum is %d%n", sum); // Sum 30 | System.out.printf("The difference is %d%n", difference); // Difference 31 | System.out.printf("The product is %d%n", product); // Product 32 | System.out.printf("The quotient is %d%n", quotient); // Quotient 33 | } // end method main 34 | } // end class Arithmetic 35 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.16/ComparingIntegers.java: -------------------------------------------------------------------------------- 1 | // Compares two integers and displays which one is bigger 2 | // @Author: Adam Janecka 3 | package pkg2_16; 4 | import java.util.Scanner; 5 | 6 | public class ComparingIntegers { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | 10 | int x; // First Integer 11 | int y; // Second Integer 12 | 13 | System.out.print("Enter first integer: "); // Prompt 14 | x = input.nextInt(); // Get First Integer 15 | 16 | System.out.print("Enter second integer: "); // Prompt 17 | y = input.nextInt(); // Get Second Integer 18 | 19 | if (x > y) // If the first 20 | System.out.printf("%d is larger%n", x); // number is larger 21 | 22 | if (x < y) // If the second 23 | System.out.printf("%d is larger%n", y); // number is larger 24 | 25 | if (x == y) 26 | System.out.println("These numbers are equal%n"); // If equal 27 | } // end method main 28 | } // end class ComparingIntegers 29 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.18/Asterisk1.java: -------------------------------------------------------------------------------- 1 | // Display shapes with asterisks 2 | // @Author: Adam Janecka 3 | package pkg2_18; 4 | 5 | public class Asterisk1 { 6 | public static void main(String[] args) { 7 | System.out.println("********* *** * *"); 8 | System.out.println("* * * * *** * *"); 9 | System.out.println("* * * * ***** * *"); 10 | System.out.println("* * * * * * *"); 11 | System.out.println("* * * * * * *"); 12 | System.out.println("* * * * * * *"); 13 | System.out.println("* * * * * * *"); 14 | System.out.println("* * * * * * *"); 15 | System.out.println("********* *** * *"); 16 | } // end method main 17 | } // end class Asterisk1 18 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.19/Asterisk2.java: -------------------------------------------------------------------------------- 1 | //Exercise 2.19 2 | // Find out what the code prints 3 | package pkg2_19; 4 | 5 | public class Asterisk2 { 6 | 7 | public static void main(String[] args) { 8 | System.out.printf("*%n**%n***%n****%n*****%n"); 9 | } // end method main 10 | } // end class Asterisk2 11 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.20/Asterisk3.java: -------------------------------------------------------------------------------- 1 | // Exercise 2.20 2 | // Find out what the code displays 3 | package pkg2_20; 4 | 5 | public class Asterisk3 { 6 | 7 | public static void main(String[] args) { 8 | System.out.println("*"); 9 | System.out.println("***"); 10 | System.out.println("*****"); 11 | System.out.println("****"); 12 | System.out.println("**"); 13 | } // end method main 14 | } // end class Asterisk3 15 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.21/Asterisk4.java: -------------------------------------------------------------------------------- 1 | // Exercise 2.21 2 | // Find out what the code displays 3 | package pkg2_21; 4 | 5 | public class Asterisk4 { 6 | 7 | public static void main(String[] args) { 8 | System.out.print("*"); 9 | System.out.print("***"); 10 | System.out.print("*****"); 11 | System.out.print("****"); 12 | System.out.println("**"); 13 | } // end method main 14 | } // end class Asterisk4 15 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.22/Asterisk.java: -------------------------------------------------------------------------------- 1 | // Exercise 2.22 2 | // Find out what the code displays 3 | 4 | package pkg2_22; 5 | 6 | public class Asterisk5 { 7 | 8 | public static void main(String[] args) { 9 | System.out.print("*"); 10 | System.out.println("***"); 11 | System.out.println("*****"); 12 | System.out.print("****"); 13 | System.out.println("**"); 14 | } // end method main 15 | } // end class Asterisk5 16 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.23/Asterisk6.java: -------------------------------------------------------------------------------- 1 | // Exercise 2.23 2 | // Find out what the code displays 3 | package pkg2_23; 4 | 5 | public class Asterisk6 { 6 | 7 | public static void main(String[] args) { 8 | System.out.printf("%s%n%s%n%s%n", "*", "***", "*****"); 9 | } // end method main 10 | } // end class Asterisk6 11 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.25/OddEven.java: -------------------------------------------------------------------------------- 1 | // Find if an integer is odd or even 2 | // @Author: Adam Janecka 3 | package pkg2_25; 4 | import java.util.Scanner; 5 | 6 | public class OddEven { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int x; // Integer inputted by user 12 | 13 | System.out.print("Enter integer: "); // Prompt 14 | x = input.nextInt(); // Get integer 15 | 16 | if (x % 2 == 0) // If the integer is even 17 | System.out.println("The integer is even."); 18 | 19 | if (x % 2 == 1) // If the integer is odd 20 | System.out.println("The integer is odd."); 21 | } // end method main 22 | } // end class OddEven 23 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.26/Multiple.java: -------------------------------------------------------------------------------- 1 | // Find if one number is a multiple of another 2 | // @Author: Adam Janecka 3 | package pkg2_26; 4 | import java.util.Scanner; 5 | 6 | public class Multiple { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int num1; // First integer 12 | int num2; // Second integer 13 | 14 | System.out.print("Enter first integer: "); // Prompt 15 | num1 = input.nextInt(); // Get first integer 16 | System.out.print("Enter second integer: "); // Prompt 17 | num2 = input.nextInt(); // Get second integer 18 | 19 | if (num2 % num1 == 0) // If the first number is a multiple 20 | System.out.println("The first integer is a multiple of the second"); 21 | else // If the first integer isn't a multiple 22 | System.out.println("The first integer is not a multiple of the second"); 23 | } // end method main 24 | } // end class Multiple 25 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.27/Asterisk.java: -------------------------------------------------------------------------------- 1 | // Create the asterisk checker pattern 2 | // @Author: Adam Janecka 3 | package pkg2_27; 4 | 5 | public class Asterisk7 { 6 | 7 | public static void main(String[] args) { 8 | 9 | System.out.println("* * * * * * * * "); 10 | System.out.println(" * * * * * * * *"); 11 | System.out.println("* * * * * * * * "); 12 | System.out.println(" * * * * * * * *"); 13 | System.out.println("* * * * * * * * "); 14 | System.out.println(" * * * * * * * *"); 15 | System.out.println("* * * * * * * * "); 16 | System.out.println(" * * * * * * * *"); 17 | 18 | } // end method main 19 | } // end class Asterisk7 20 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.28/Circle.java: -------------------------------------------------------------------------------- 1 | // Find the diameter, circumference, and area of a circle 2 | // @Author: Adam Janecka 3 | package pkg2_28; 4 | import java.util.Scanner; 5 | 6 | public class Circle { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int radius; // The radius entered by user 12 | 13 | System.out.print("Enter radius: "); // Prompt 14 | radius = input.nextInt(); // Get radius 15 | 16 | System.out.printf("Diameter is %d%n", (radius * 2)); 17 | System.out.printf("Circumference is %f%n", (2 * radius * Math.PI)); 18 | System.out.printf("Area is %f%n", (radius * radius * Math.PI)); 19 | } // end method main 20 | } // end class Circle 21 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.29/IntegerValue.java: -------------------------------------------------------------------------------- 1 | // Show the ASCII representation of a few characters 2 | // @Author: Adam Janecka 3 | package pkg2_29; 4 | 5 | public class IntegerValue { 6 | 7 | public static void main(String[] args) { 8 | 9 | System.out.printf("The character %c has the value %d%n", 'A', ((int) 'A')); 10 | System.out.printf("The character %c has the value %d%n", 'B', ((int) 'B')); 11 | System.out.printf("The character %c has the value %d%n", 'C', ((int) 'C')); 12 | System.out.printf("The character %c has the value %d%n", 'a', ((int) 'a')); 13 | System.out.printf("The character %c has the value %d%n", 'b', ((int) 'b')); 14 | System.out.printf("The character %c has the value %d%n", 'c', ((int) 'c')); 15 | System.out.printf("The character %c has the value %d%n", '0', ((int) '0')); 16 | System.out.printf("The character %c has the value %d%n", '1', ((int) '1')); 17 | System.out.printf("The character %c has the value %d%n", '2', ((int) '2')); 18 | System.out.printf("The character %c has the value %d%n", '$', ((int) '$')); 19 | System.out.printf("The character %c has the value %d%n", '*', ((int) '*')); 20 | System.out.printf("The character %c has the value %d%n", '+', ((int) '+')); 21 | System.out.printf("The character %c has the value %d%n", '/', ((int) '/')); 22 | System.out.printf("The character %c has the value %d%n", ' ', ((int) ' ')); 23 | } // end method main 24 | } // end class IntegerValue 25 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.30/SeparateDigit.java: -------------------------------------------------------------------------------- 1 | // Separate the digits of a number and output them back to the user 2 | // @Author: Adam Janecka 3 | package pkg2_30; 4 | import java.util.Scanner; 5 | 6 | public class SeparateDigit { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int number; // Five digit number 12 | int digit1; // 10000's Place digit 13 | int digit2; // 1000's Place digit 14 | int digit3; // 100's Place digit 15 | int digit4; // 10's Place digit 16 | int digit5; // 1's Place digit 17 | 18 | System.out.print("Enter a five digit number: "); //prompt 19 | number = input.nextInt(); // Get Integer 20 | 21 | digit1 = number / 10000; // Obtain digits 22 | number = number % 10000; 23 | digit2 = number / 1000; 24 | number = number % 1000; 25 | digit3 = number / 100; 26 | number = number % 100; 27 | digit4 = number / 10; 28 | digit5 = number % 10; 29 | 30 | System.out.printf("The digits are %d %d %d %d %d%n", digit1, digit2, 31 | digit3, digit4, digit5); 32 | } // end method main 33 | } // end class SeparateDigit 34 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.31/SquareCube.java: -------------------------------------------------------------------------------- 1 | // Create a table showing the square and cubes of numbers 0-10 2 | // @Author: Adam Janecka 3 | package pkg2_31; 4 | 5 | public class SquareCube { 6 | 7 | public static void main(String[] args) { 8 | 9 | System.out.println("number square cube"); 10 | System.out.printf("%d\t%d\t%d%n", 0, 0 * 0, 0 * 0 * 0); 11 | System.out.printf("%d\t%d\t%d%n", 1, 1 * 1, 1 * 1 * 1); 12 | System.out.printf("%d\t%d\t%d%n", 2, 2 * 2, 2 * 2 * 2); 13 | System.out.printf("%d\t%d\t%d%n", 3, 3 * 3, 3 * 3 * 3); 14 | System.out.printf("%d\t%d\t%d%n", 4, 4 * 4, 4 * 4 * 4); 15 | System.out.printf("%d\t%d\t%d%n", 5, 5 * 5, 5 * 5 * 5); 16 | System.out.printf("%d\t%d\t%d%n", 6, 6 * 6, 6 * 6 * 6); 17 | System.out.printf("%d\t%d\t%d%n", 7, 7 * 7, 7 * 7 * 7); 18 | System.out.printf("%d\t%d\t%d%n", 8, 8 * 8, 8 * 8 * 8); 19 | System.out.printf("%d\t%d\t%d%n", 9, 9 * 9, 9 * 9 * 9); 20 | System.out.printf("%d\t%d\t%d%n", 10, 10 * 10, 10 * 10 * 10); 21 | 22 | } // end method main 23 | } // end class SquareCube 24 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.33/BMI.java: -------------------------------------------------------------------------------- 1 | // BMI Calculator 2 | // @Author: Adam Janecka 3 | package pkg2_33; 4 | import java.util.Scanner; 5 | 6 | public class BMI { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int weight; // Weight in pounds 12 | int height; // Height in inches 13 | int BMI; // Body Mass Index 14 | 15 | System.out.print("Enter weight in pounds: "); // Prompt 16 | weight = input.nextInt(); // Get weight 17 | System.out.print("Enter height in inches: "); // Prompt 18 | height = input.nextInt(); // Get height 19 | 20 | BMI = (weight * 703) / (height * height); // Calculate BMI 21 | System.out.printf("Your BMI is %d%n", BMI); 22 | 23 | if (BMI < 18.5) //Display correct BMI statement 24 | System.out.println("Your BMI is Underweight\n"); 25 | if (BMI >= 18.5 && BMI <= 24.9) 26 | System.out.println("Your BMI is Normal\n"); 27 | if (BMI >= 25 && BMI <= 29.9) 28 | System.out.println("Your BMI is Overweight\n"); 29 | if (BMI > 30) 30 | System.out.println("Your BMI is Obese\n"); 31 | 32 | System.out.println("BMI Values"); //BMI info from Department of Health 33 | System.out.println("Underweight:\tless than 18.5"); 34 | System.out.println("Normal:\t\tbetween 18.5 and 24.9"); 35 | System.out.println("Overweight:\tbetween 25 and 29.9"); 36 | System.out.println("Obese:\t\t30 or greater"); 37 | } // end method main 38 | } // end class BMI 39 | -------------------------------------------------------------------------------- /Chapter02/Exercises/2.34/WorldPopulation.java: -------------------------------------------------------------------------------- 1 | // Find the world population and calculate population growth 2 | // @Author: Adam Janecka 3 | package pkg2_34; 4 | import java.util.Scanner; 5 | 6 | public class WorldPopulation { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | double worldpop; // Current world population 12 | double popgrowth; // Population growh rate 13 | 14 | System.out.print("Enter current world population: "); // Prompt 15 | worldpop = input.nextDouble(); // Get World Population 16 | System.out.print("Enter current population growth rate: "); // Prompt 17 | popgrowth = input.nextDouble(); // Get growth rate 18 | 19 | System.out.printf("Population in 1 year: %f%n", worldpop * popgrowth); 20 | System.out.printf("Population in 2 year: %f%n", worldpop * popgrowth * popgrowth); 21 | System.out.printf("Population in 3 year: %f%n", worldpop * popgrowth * popgrowth 22 | * popgrowth); 23 | System.out.printf("Population in 4 year: %f%n", worldpop * popgrowth * popgrowth 24 | * popgrowth * popgrowth); 25 | System.out.printf("Population in 5 year: %f%n", worldpop * popgrowth * popgrowth 26 | * popgrowth * popgrowth * popgrowth); 27 | } // end method main 28 | } // end class WorldPopulation 29 | -------------------------------------------------------------------------------- /Chapter03/Examples/3.06/ClassAverage.java: -------------------------------------------------------------------------------- 1 | // Fig. 3.6: ClassAverage.java 2 | // Solving the class-average problem using counter-controlled repetition. 3 | package pkg3_06; 4 | import java.util.Scanner; // program uses Class Scanner 5 | 6 | public class ClassAverage 7 | { 8 | public static void main(String[] args) { 9 | // create Scanner to obtain input from command window 10 | Scanner input = new Scanner(System.in); 11 | 12 | // initialization phase 13 | int total = 0; // initialize sum of grades entered by the user 14 | int gradeCounter = 1; // initialize # of grade to be entered next 15 | 16 | // processing phase uses counter-controlled repetition 17 | while (gradeCounter <= 10) // loop 10 times 18 | { 19 | System.out.print("Enter grade: "); // prompt 20 | int grade = input.nextInt(); // input next grade 21 | total = total + grade; // add grade to total 22 | gradeCounter = gradeCounter + 1; // increment counter by 1 23 | } 24 | 25 | // termination phase 26 | int average = total / 10; // integer division yields integer result 27 | 28 | // display total and average of grades 29 | System.out.printf("%nTotal of all 10 grades is %d%n", total); 30 | System.out.printf("Class average is %d%n", average); 31 | } // end method main 32 | } // end class ClassAverage 33 | -------------------------------------------------------------------------------- /Chapter03/Examples/3.10/Analysis.java: -------------------------------------------------------------------------------- 1 | // Fig. 3.10: Analysis.java 2 | // Analysis of examination results using nested control statements. 3 | package pkg3_10; 4 | import java.util.Scanner; // class uses class Scanner 5 | 6 | public class Analysis { 7 | 8 | public static void main(String[] args) { 9 | 10 | // create Scanner to obtain input from command window 11 | Scanner input = new Scanner (System.in); 12 | 13 | // initializing variables in declarations 14 | int passes = 0; 15 | int failures = 0; 16 | int studentCounter = 1; 17 | 18 | // process 10 students using counter-controlled loop 19 | while (studentCounter <= 10) 20 | { 21 | // prompt user for input and obtain value from user 22 | System.out.print("Enter result (1 = pass, 2 = fail): "); 23 | int result = input.nextInt(); 24 | 25 | // if...else is nested in the while statement 26 | if (result == 1) 27 | passes = passes + 1; 28 | else 29 | failures = failures + 1; 30 | 31 | // increment studentCounter so loop eventually terminates 32 | studentCounter = studentCounter + 1; 33 | } 34 | 35 | // termination phase; prepare and display results 36 | System.out.printf("Passed: %d%nFailed %d%n", passes, failures); 37 | 38 | // determine whether more than 8 students passed 39 | if (passes > 8) 40 | System.out.println("Bonus to instructor!"); 41 | } // end method main 42 | } // end class Analysis 43 | -------------------------------------------------------------------------------- /Chapter03/Examples/3.13/Increment.java: -------------------------------------------------------------------------------- 1 | // Fig. 3.13: Increment.java 2 | // Prefix increment and postfix increment operators 3 | package pkg3_13; 4 | 5 | public class Increment { 6 | 7 | public static void main(String[] args) { 8 | 9 | // demonstrate postfix increment operator 10 | int c = 5; 11 | System.out.printf("c before postincrement: %d%n", c); // prints 5 12 | System.out.printf(" postincrementing c: %d%n", c++); // prints 5 13 | System.out.printf(" c after postincrement: %d%n", c); 14 | 15 | System.out.println(); // skip a line 16 | 17 | // demonstrate prefix increment operator 18 | c = 5; 19 | System.out.printf(" c before preincrement: %d%n", c); // prints 5 20 | System.out.printf(" preincrementing c: %d%n", ++c); // prints 6 21 | System.out.printf(" c after preincrement: %d%n", c); // prints 6 22 | } // end method main 23 | } // end class Increment 24 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.06/Calculate.java: -------------------------------------------------------------------------------- 1 | // Fig. 3.13: Increment.java 2 | // Prefix increment and postfix increment operators 3 | package pkg3_13; 4 | 5 | public class Increment { 6 | 7 | public static void main(String[] args) { 8 | 9 | // demonstrate postfix increment operator 10 | int c = 5; 11 | System.out.printf("c before postincrement: %d%n", c); // prints 5 12 | System.out.printf(" postincrementing c: %d%n", c++); // prints 5 13 | System.out.printf(" c after postincrement: %d%n", c); 14 | 15 | System.out.println(); // skip a line 16 | 17 | // demonstrate prefix increment operator 18 | c = 5; 19 | System.out.printf(" c before preincrement: %d%n", c); // prints 5 20 | System.out.printf(" preincrementing c: %d%n", ++c); // prints 6 21 | System.out.printf(" c after preincrement: %d%n", c); // prints 6 22 | } // end method main 23 | } // end class Increment 24 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.16/Mystery.java: -------------------------------------------------------------------------------- 1 | // Exercise 3.16: Mystery.java 2 | package pkg3_16; 3 | 4 | public class Mystery { 5 | 6 | public static void main(String[] args) { 7 | 8 | int x = 1; 9 | int total = 0; 10 | 11 | while (x <= 10) 12 | { 13 | int y = x * x; 14 | System.out.println(y); 15 | total += y; 16 | ++x; 17 | } 18 | 19 | System.out.printf("Total is %d%n", total); 20 | } // end method main 21 | } // end class Mystery 22 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.17/GasMileage.java: -------------------------------------------------------------------------------- 1 | // Display the total gas mileage and gas mileage for each trip 2 | // @Author: Adam Janecka 3 | package pkg3_17; 4 | import java.util.Scanner; 5 | 6 | public class GasMileage { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner (System.in); 11 | 12 | int miles; // Miles for each individual trip 13 | int gallon; // Gallons for each individual trip 14 | int totalmiles = 0; // Miles for all trips 15 | int totalgallon = 0; // Gallons for all combined trips 16 | 17 | System.out.print("Enter miles for trip or -1 to quit: "); 18 | miles = input.nextInt(); // obtain first trip's miles 19 | 20 | while (miles != -1) 21 | { 22 | totalmiles += miles; // add to total 23 | System.out.print("Enter gallons of gas used: "); 24 | gallon = input.nextInt(); // obtain gallons 25 | totalgallon += gallon; 26 | 27 | System.out.printf("Miles driven for this trip: %d%n", miles); // Information displayed 28 | System.out.printf("Gallons used on this trip: %d%n", gallon); // for user 29 | System.out.printf("Average mpg on this trip: %f%n", (double)miles/gallon); 30 | System.out.printf("Average mpg overall: %f%n", (double)totalmiles/totalgallon); 31 | 32 | System.out.print("Enter miles for next trip or -1 to quit: "); 33 | miles = input.nextInt(); // Prevents infinite loop 34 | } // end while loop 35 | } // end method main 36 | } // end class GasMileage 37 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.20/Salary.java: -------------------------------------------------------------------------------- 1 | // Calculate salary for three employees 2 | // @Author: Adam Janecka 3 | package pkg3_20; 4 | import java.util.Scanner; 5 | 6 | public class Salary { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int hours; // Number of hours worked 12 | double rate; // Hourly rate of work 13 | double salary; // Total earnings for the week 14 | 15 | System.out.print("Enter number of hours worked or -1 to quit: "); 16 | hours = input.nextInt(); 17 | 18 | while (hours != -1) // sentinel controlled loop 19 | { 20 | System.out.print("Enter hourly wage rate: "); 21 | rate = input.nextDouble(); 22 | 23 | if (hours <= 40) // If they didn't work overtime 24 | { 25 | salary = hours * rate; 26 | System.out.printf("Total earnings: $%.2f%n", salary); 27 | } 28 | else // If they worked overtime 29 | { 30 | salary = (rate * 40) + ((hours - 40) * (rate * 1.5)); // Calculating overtime 31 | System.out.printf("Total earning: $%.2f%n%n", salary); 32 | } 33 | 34 | System.out.print("Enter hours worked or -1 to quit: "); 35 | hours = input.nextInt(); 36 | } // end while loop 37 | } // end method main 38 | } // end class Salary 39 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.21/Largest.java: -------------------------------------------------------------------------------- 1 | // Find the largest integer out of ten numbers 2 | // @Author: Adam Janecka 3 | package pkg3_21; 4 | import java.util.Scanner; 5 | 6 | public class Largest { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int counter = 1; // counter for the while loop 12 | int number; // Number input by the user 13 | int largest; // Largest number so far 14 | 15 | 16 | System.out.print("Enter number: "); 17 | number = input.nextInt(); 18 | largest = number; // Largest is first number by default 19 | 20 | while (counter < 10) 21 | { 22 | System.out.print("Enter number: "); 23 | number = input.nextInt(); 24 | if (number > largest) // If the new number is bigger 25 | largest = number; 26 | 27 | counter++; // While loop counter update 28 | } // end while loop 29 | 30 | System.out.printf("Largest number: %d%n", largest); // output largest 31 | 32 | } // end method main 33 | } // end class Largest 34 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.22/Table10.java: -------------------------------------------------------------------------------- 1 | // Output table of values using while loops 2 | // @Author: Adam Janecka 3 | package pkg3_22; 4 | 5 | public class Table10 { 6 | 7 | public static void main(String[] args) { 8 | 9 | int n = 1; // counter variable 10 | 11 | System.out.println("N\t10*N\t100*N\t1000*N"); 12 | 13 | while (n <= 5) 14 | { 15 | System.out.printf("%d\t%d\t%d\t%d\t%n", n, n * 10, n * 100, n * 1000); 16 | n++; 17 | } // end while loop 18 | } // end method main 19 | } // end class Table10 20 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.23/TwoLargest.java: -------------------------------------------------------------------------------- 1 | // Find the two largest numbers from a group of 10 2 | // @Author: Adam Janecka 3 | package pkg3_23; 4 | import java.util.Scanner; 5 | 6 | public class TwoLargest { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int counter = 1; // counter for while loop 12 | int number; // number input by user 13 | int largest; // largest number 14 | int largest2; // second largest number 15 | 16 | System.out.print("Enter number: "); 17 | number = input.nextInt(); 18 | largest = number; // Largest number is the first number by default 19 | largest2 = number; // Set second largest as default 20 | 21 | while (counter < 10) 22 | { 23 | System.out.print("Enter number: "); 24 | number = input.nextInt(); 25 | 26 | if (number > largest) 27 | { 28 | largest2 = largest; // Largest number becomes second largest 29 | largest = number; // New number is largest 30 | } 31 | 32 | if (number < largest && number > largest2) // If number is second highest 33 | { 34 | largest2 = number; 35 | } 36 | counter++; 37 | } // end while loop 38 | 39 | System.out.printf("Largest number: %d%n", largest); 40 | System.out.printf("Second largest number: %d%n", largest2); 41 | 42 | } // end method main 43 | } // end class TwoLargest 44 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.25/Mystery2.java: -------------------------------------------------------------------------------- 1 | // Exercise 3.25: Mystery2.java 2 | package pkg3_25; 3 | 4 | public class Mystery2 { 5 | 6 | public static void main(String[] args) { 7 | 8 | int count = 1; 9 | 10 | while (count <= 10) 11 | { 12 | System.out.println(count % 2 == 1 ? "****" : "++++++++"); 13 | ++count; 14 | } // end while loop 15 | } // end method main 16 | } // end class Mystery2 17 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.26/Mystery3.java: -------------------------------------------------------------------------------- 1 | // Exercise 3.26: Mystery3.java 2 | package pkg3_26; 3 | 4 | public class Mystery3 { 5 | 6 | public static void main(String[] args) { 7 | 8 | int row = 10; 9 | 10 | while (row >= 1) 11 | { 12 | int column = 1; 13 | 14 | while (column <= 10) 15 | { 16 | System.out.print(row % 2 == 1 ? "<" : ">"); 17 | ++ column; 18 | } 19 | 20 | --row; 21 | System.out.println(); 22 | } // end while loop 23 | } // end method main 24 | } // end class Mystery3 25 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.27/DanglingElse.java: -------------------------------------------------------------------------------- 1 | // Determine the output of code when x is 9 and y is 11 2 | package pkg3_27; 3 | 4 | public class DanglingElse { 5 | 6 | public static void main(String[] args) { 7 | 8 | int x = 9; 9 | int y = 11; 10 | 11 | // Exercise 3.27a 12 | System.out.println("Exercise 3.27a"); 13 | 14 | if (x < 10) 15 | if (y > 10) 16 | System.out.println("*****"); 17 | else 18 | System.out.println("#####"); 19 | System.out.println("$$$$$"); 20 | System.out.println(); 21 | 22 | // Exercise 3.27b 23 | System.out.println("Exercise 3.27b"); 24 | 25 | if (x < 10) 26 | { 27 | if (y > 10) 28 | System.out.println("*****"); 29 | } 30 | else 31 | { 32 | System.out.println("#####"); 33 | System.out.println("$$$$$"); 34 | } 35 | } // end method main 36 | } // end class DanglingElse 37 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.29/AsteriskSquare.java: -------------------------------------------------------------------------------- 1 | // Create a square of asterisks based on user input 2 | // @Author: Adam Janecka 3 | package pkg3_29; 4 | import java.util.Scanner; 5 | 6 | public class AsteriskSquare { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int size; // Size of square input by user 12 | int row = 0; // Row counter 13 | int column = 0; // Column counter 14 | 15 | System.out.print("Enter size of square between 1 and 20: "); 16 | size = input.nextInt(); 17 | 18 | while (size <= 1 || size >= 20) // Refuses value not between 1 and 20 19 | { 20 | System.out.print("Incorrect value. Enter value between 1 and 20: "); 21 | size = input.nextInt(); 22 | } 23 | 24 | while (column < size) 25 | { 26 | row = 0; 27 | 28 | while (row < size) 29 | { 30 | System.out.print("*"); 31 | row++; 32 | } 33 | System.out.println(); 34 | column++; 35 | } // end while loop 36 | } // end method main 37 | } // end class AsteriskSquare 38 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.30/Palindrome.java: -------------------------------------------------------------------------------- 1 | // Determine whether a five digit number is a palindrome 2 | // @Author: Adam Janecka 3 | package pkg3_30; 4 | import java.util.Scanner; 5 | 6 | public class Palindrome { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner (System.in); 11 | int number; // Number input by user 12 | int digit1; // 1's Digit 13 | int digit2; // 10's Digit 14 | int digit3; // 100's Digit 15 | int digit4; // 1000's Digit 16 | int digit5; // 10000's Digit 17 | 18 | System.out.print("Enter a five digit number: "); 19 | number = input.nextInt(); 20 | 21 | while (number < 10000 || number > 99999) 22 | { 23 | System.out.print("Incorrect value. Enter a five digit number: "); 24 | number = input.nextInt(); 25 | } 26 | 27 | digit1 = number % 10; // Put each digit as a variable 28 | digit2 = (number % 100 - digit1) / 10; 29 | digit3 = (number % 1000 - digit2 - digit1) / 100; 30 | digit4 = (number % 10000 - digit3 - digit2 - digit1) / 1000; 31 | digit5 = (number % 100000 - digit4 - digit3 - digit2 - digit1) / 10000; 32 | 33 | if (digit1 != digit5) 34 | System.out.println("The number is not a palindrome."); 35 | else if (digit2 != digit4) 36 | System.out.println("The number is not a palindrome."); 37 | else 38 | System.out.println("The number is a palindrome."); 39 | } // end method main 40 | } // end class Palindrome 41 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.31/BinarytoDecimal.java: -------------------------------------------------------------------------------- 1 | // Converts a binary number to a decimal number 2 | // @Author: Adam Janecka 3 | package pkg3_31; 4 | import java.util.Scanner; 5 | 6 | public class BinarytoDecimal { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner (System.in); 11 | int bin; // Binary number input by user 12 | int remainder; //Remainder variable used in calculation 13 | int decimal = 0; // Decimal output 14 | int power = 0; // Power variable used in calculation 15 | 16 | System.out.print("Enter binary number: "); 17 | bin = input.nextInt(); 18 | 19 | while (bin != 0) 20 | { 21 | remainder = bin % 10; 22 | decimal = (int)(decimal + remainder * Math.pow(2, power)); 23 | bin = bin / 10; 24 | power++; 25 | } // end while loop 26 | 27 | System.out.printf("The number as decimal is: %d%n", decimal); 28 | 29 | } // end method main 30 | } // end class BinarytoDecimal 31 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.32/AsteriskChecker.java: -------------------------------------------------------------------------------- 1 | // Create Asterisk pattern 2 | // @Author: Adam Janecka 3 | package pkg3_32; 4 | 5 | public class AsteriskChecker { 6 | 7 | public static void main(String[] args) { 8 | 9 | int counter = 0; // Used for while loop 10 | int counter2 = 0; // Used for each line 11 | while (counter < 8) 12 | { 13 | if (counter % 2 == 1) 14 | System.out.print(" "); 15 | 16 | counter2 = 0; // Resets counter2 17 | 18 | while (counter2 < 8) 19 | { 20 | System.out.print("*"); 21 | System.out.print(" "); 22 | counter2++; 23 | } 24 | System.out.println(); 25 | counter++; 26 | } // end while loop 27 | } // end method main 28 | } // end class Asterisk Checker 29 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.33/InfiniteTwo.java: -------------------------------------------------------------------------------- 1 | // Create an infinite loop showing the multiples of 2 2 | // @Author: Adam Janecka 3 | package pkg3_33; 4 | 5 | public class InfiniteTwo { 6 | 7 | public static void main(String[] args) { 8 | 9 | int counter = 1; // used for while loop 10 | 11 | while (counter > 0) 12 | { 13 | System.out.printf("%d%n", 2 * counter); 14 | counter++; 15 | } // end while loop 16 | } // end method main 17 | } // end class InfiniteTwo 18 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.34/IncrementError.java: -------------------------------------------------------------------------------- 1 | // Fix code in Exercise 3.34 2 | package pkg3_34; 3 | 4 | public class IncrementError { 5 | 6 | public static void main(String[] args) { 7 | 8 | int x = 5; 9 | int y = 6; 10 | 11 | System.out.printf("x + y is %d%n", x + y); 12 | System.out.printf("x + y + 1 is %d%n", ++x + y); 13 | } // end method main 14 | } // end class IncrementError 15 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.35/Triangle.java: -------------------------------------------------------------------------------- 1 | // Find if three values make a triangle 2 | // @Author: Adam Janecka 3 | package pkg3_35; 4 | import java.util.Scanner; 5 | 6 | public class Triangle { 7 | 8 | public static void main(String[] args){ 9 | 10 | Scanner input = new Scanner(System.in); 11 | int num1; // first number 12 | int num2; // second number 13 | int num3; // third number 14 | 15 | System.out.print("Enter first number: "); 16 | num1 = input.nextInt(); 17 | System.out.print("Enter second number: "); 18 | num2 = input.nextInt(); 19 | System.out.print("Enter third number: "); 20 | num3 = input.nextInt(); 21 | 22 | if (num1 + num2 <= num3) 23 | System.out.println("These numbers cannot form a triangle."); 24 | else if (num1 + num3 <= num2) 25 | System.out.println("These numbers cannot form a trinagle."); 26 | else if (num2 + num3 <= num1) 27 | System.out.println("These numbers cannot form a triangle."); 28 | else 29 | System.out.println("These numbers can form a triangle."); 30 | } // end method main 31 | } // end class Triangle 32 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.36/RightTriangle.java: -------------------------------------------------------------------------------- 1 | // Find out if three number make a right triangle 2 | // @Author: Adam Janecka 3 | package pkg3_36; 4 | import java.util.Scanner; 5 | 6 | public class RightTriangle { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner (System.in); 11 | double num1; // First number 12 | double num2; // Second number 13 | double num3; // Third number 14 | 15 | System.out.print("Enter first number: "); 16 | num1 = input.nextDouble(); 17 | System.out.print("Enter second number: "); 18 | num2 = input.nextDouble(); 19 | System.out.print("Enter third number: "); 20 | num3 = input.nextDouble(); 21 | 22 | if (num1 * num1 + num2 * num2 == num3 * num3) 23 | System.out.println("These number can make a right triangle."); 24 | else if (num1 * num1 + num3 * num3 == num2 * num2) 25 | System.out.println("These number can make a right triangle."); 26 | else if (num2 * num2 + num3 * num3 == num1 * num1) 27 | System.out.println("These number can make a right triangle."); 28 | else 29 | System.out.println("These numbers cannot make a right triangle."); 30 | } // end method main 31 | } // end class RightTriangle 32 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.37a/Factorial.java: -------------------------------------------------------------------------------- 1 | // Calculate factorial of number entered by user 2 | // @Author: Adam Janecka 3 | package pkg3_37a; 4 | import java.util.Scanner; 5 | 6 | public class Factorial { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int number; // Number input by user 12 | int counter; // used for while loop 13 | int factorial; // Factorial of user input 14 | 15 | System.out.print("Enter number: "); 16 | number = input.nextInt(); 17 | counter = number; 18 | factorial = number; 19 | 20 | while (counter > 1) 21 | { 22 | factorial = factorial * (counter - 1); 23 | counter--; 24 | } 25 | 26 | System.out.printf("%d! is %d%n", number, factorial); 27 | } // end method main 28 | } // end class Factorial 29 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.37b/Factoriale.java: -------------------------------------------------------------------------------- 1 | // Find the value of mathematical constant e to a certain number of terms 2 | // @Author: Adam Janecka 3 | package pkg3_37b; 4 | import java.util.Scanner; 5 | 6 | public class Factoriale { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int number; // Number input by user 12 | int i = 1; // Used for while loop 13 | float e = 1; // Value of e 14 | 15 | System.out.print("Enter number of terms to calculate the value of e: "); 16 | number = input.nextInt(); 17 | 18 | while (i <= number) 19 | { 20 | int result = 1; // Used for factorial 21 | int j = 1; 22 | while (j <= i) 23 | { 24 | result = result * j; //Calculates the factorial 25 | j++; 26 | } 27 | 28 | e += 1 / (float)result; 29 | i++; 30 | } // end while loop 31 | 32 | System.out.printf("The value of e is %f%n", e); 33 | 34 | } // end method main 35 | } // end class Factoriale 36 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.37c/FactorialEx.java: -------------------------------------------------------------------------------- 1 | // Calculate e^x to a set number of terms 2 | // @Author: Adam Janecka 3 | package pkg3_37c; 4 | import java.util.Scanner; 5 | 6 | public class FactorialEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int number; // Number of terms input by user 12 | int i = 1; // Used in while loop 13 | int x; // Value of x in e^x 14 | float e = 1; // Default value of e 15 | 16 | System.out.print("Enter number of terms to calculate e^x: "); 17 | number = input.nextInt(); 18 | System.out.print("Enter value for x: "); 19 | x = input.nextInt(); 20 | 21 | while (i <= number) 22 | { 23 | int result = 1; // Used for factorial 24 | int j = 1; 25 | while (j <= i) 26 | { 27 | result = result * j; //Calculates the factorial 28 | j++; 29 | } 30 | 31 | e += Math.pow(x, i) / (float)result; 32 | i++; 33 | } // end while loop 34 | 35 | System.out.printf("The value of e is %f%n", e); 36 | 37 | } // end method main 38 | } // end 39 | -------------------------------------------------------------------------------- /Chapter03/Exercises/3.39/GlobalPopulation.java: -------------------------------------------------------------------------------- 1 | // Estimate the global population for the next 75 years 2 | // @Author: Adam Janecka 3 | package pkg3_39; 4 | 5 | public class GlobalPopulation { 6 | 7 | public static void main(String[] args) { 8 | 9 | int counter = 2017; // used for while loop 10 | double population = 7.5; // Calculated in billions 11 | double growthrate = 1.11; 12 | int twice; // Year population is twice current 13 | int x = 1; // Used to calculate when population doubles 14 | 15 | System.out.println("Year\tPopulation (Billions)\tIncrease"); 16 | System.out.println("2017\t7.5 Billion\t\t0"); 17 | 18 | while (population < 15) 19 | { 20 | System.out.printf("%d\t%.2f\t\t\t%.2f%n", counter + 1, population * growthrate 21 | , population * 0.11); 22 | population = population * growthrate; 23 | counter++; 24 | 25 | } // end while loop 26 | 27 | twice = counter; // Stores the year the population doubles to be displayed at the end 28 | 29 | while (counter < 2092) 30 | { 31 | System.out.printf("%d\t%.2f\t\t\t%.2f%n", counter + 1, population * growthrate 32 | , population * 0.11); 33 | population = population * growthrate; 34 | counter++; 35 | 36 | } // end while loop 37 | 38 | System.out.printf("%nThe population doubles in the year %d%n.", twice); 39 | 40 | } // end method main 41 | } // end class GlobalPopulation 42 | -------------------------------------------------------------------------------- /Chapter04/Examples/4.01/WhileCounter.java: -------------------------------------------------------------------------------- 1 | // Fig. 4.1: WhileCounter.java 2 | // Counter-controlled repetition with the while repetition statement 3 | package pkg4_01; 4 | 5 | public class WhileCounter { 6 | 7 | public static void main(String[] args) { 8 | 9 | int counter = 1; // declare and initialize control variable 10 | 11 | while (counter <= 10) // loop continuation condition 12 | { 13 | System.out.printf("%d ", counter); 14 | ++counter; // increment control variable 15 | } 16 | System.out.println(); 17 | 18 | } // end method main 19 | } // end class WhileCounter 20 | -------------------------------------------------------------------------------- /Chapter04/Examples/4.02/ForCounter.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter04/Examples/4.05/Sum.java: -------------------------------------------------------------------------------- 1 | // Fig 4.5: Sum.java 2 | // Summing integers with the for statement 3 | package pkg4_05; 4 | 5 | public class Sum { 6 | 7 | public static void main(String[] args) { 8 | 9 | int total = 0; 10 | 11 | // total even integers from 2 through 20 12 | for (int number = 2; number <= 20; number += 2) 13 | total += number; 14 | 15 | System.out.printf("Sum is %d%n", total); 16 | } // end method main 17 | } // end class Sum 18 | -------------------------------------------------------------------------------- /Chapter04/Examples/4.06/Interest.java: -------------------------------------------------------------------------------- 1 | // Fig. 4.6: Interest.java 2 | // Compound-iterest calculations with for. 3 | package pkg4_06; 4 | 5 | public class Interest { 6 | 7 | public static void main(String[] args) { 8 | 9 | double amount; // amount on deposit at end of each year 10 | double principal = 1000.0; // initial amount before interest 11 | double rate = 0.05; // interest rate 12 | 13 | // display headers 14 | System.out.printf("%s%20s%n", "Year", "Amount on deposit"); 15 | 16 | // calculate amount on deposit for each of ten years 17 | for (int year = 1; year <= 10; ++year) 18 | { 19 | // calculate new amount for specified year 20 | amount = principal * Math.pow(1.0 + rate, year); 21 | 22 | // display the year and the amount 23 | System.out.printf("%4d%,20.2f%n", year, amount); 24 | } 25 | } // end method main 26 | } // end class Interest 27 | -------------------------------------------------------------------------------- /Chapter04/Examples/4.07/DoWhileTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 4.7: DoWhileTest.java 2 | // do...while repetition statement. 3 | package pkg4_07; 4 | 5 | public class DoWhileTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | int counter = 1; 10 | 11 | do 12 | { 13 | System.out.printf("%d ", counter); 14 | ++counter; 15 | } while (counter <= 10); // end do...while 16 | 17 | System.out.println(); 18 | } // end method main 19 | } // end class DoWhileTest 20 | -------------------------------------------------------------------------------- /Chapter04/Examples/4.11/BreakTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 4.11: BreakTest.java 2 | // break statement exiting a for statement. 3 | package pkg4_11; 4 | 5 | public class BreakTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | int count; // control variable also used after loop terminates 10 | 11 | for (count = 1; count <= 10; count++) // loop 10 times 12 | { 13 | if (count == 5) 14 | break; // terminates loop if count is 5 15 | 16 | System.out.printf("%d ", count); 17 | } 18 | 19 | System.out.printf("%nBroke out of loop at count = %d%n", count); 20 | } // end method main 21 | } // end class BreakTest 22 | -------------------------------------------------------------------------------- /Chapter04/Examples/4.12/ContinueTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 4.12: ContinueTest.java 2 | // continue statement terminating an interation of a for statement. 3 | package pkg4_12; 4 | 5 | public class ContinueTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | for (int count = 1; count <= 10; count++) // loop 10 times 10 | { 11 | if (count == 5) 12 | continue; // skip remaining code in loop body if count is 5 13 | 14 | System.out.printf("%d ", count); 15 | } 16 | 17 | System.out.printf("%nUsed continue to skip printing 5%n"); 18 | } // end method main 19 | } // end class ContinueTest 20 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.10/Printing.java: -------------------------------------------------------------------------------- 1 | // Exercise 4.10: Printing.java 2 | package pkg4_10; 3 | 4 | public class Printing { 5 | 6 | public static void main(String[] args) { 7 | 8 | for (int i = 1; i <= 10; i++) 9 | { 10 | for (int j = 1; j <= 5; j++) 11 | System.out.print('@'); 12 | 13 | System.out.println(); 14 | } 15 | } // end method main 16 | } // end class Printing 17 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.11/SmallestValue.java: -------------------------------------------------------------------------------- 1 | // Find the smallest value of a list entered by the user 2 | // @Author: Adam Janecka 3 | package pkg4_11; 4 | import java.util.Scanner; 5 | 6 | public class SmallestValue { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int count; // number of integers entered by user 12 | int number; // The numbers input by user 13 | int smallest = 0; // The smallest value 14 | 15 | System.out.print("Enter how many values you are going to input: "); 16 | count = input.nextInt(); 17 | 18 | for (int i = 1; i <= count; i++) 19 | { 20 | System.out.print("Enter number: "); 21 | number = input.nextInt(); 22 | 23 | if (i == 1) // sets the first number as default smallest number 24 | smallest = number; 25 | 26 | if (number < smallest) 27 | smallest = number; 28 | } // end for loop 29 | 30 | System.out.printf("The smallest number is %d%n", smallest); 31 | 32 | } // end method main 33 | } // end class SmallestValue 34 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.12/Product.java: -------------------------------------------------------------------------------- 1 | // Calculate the product of odd integers from 1 to 15 2 | // @Author: Adam Janecka 3 | package pkg4_12; 4 | 5 | public class Product { 6 | 7 | public static void main(String[] args) { 8 | 9 | int product = 1; // The product of all the numbers 10 | 11 | for (int i = 1; i <= 15; i += 2) 12 | product *= i; 13 | 14 | System.out.printf("The product of all odd integers from 1 to 15 is %d%n", product); 15 | } // end method main 16 | } // end class Product 17 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.13/Factorial.java: -------------------------------------------------------------------------------- 1 | // Print the factorials of all integers from 1 to 20 2 | // @Author: Adam Janecka 3 | package pkg4_13; 4 | 5 | public class Factorial { 6 | 7 | public static void main(String[] args) { 8 | 9 | long number = 1; // Integer used to calculate factorial 10 | 11 | System.out.printf("Number\tFactorial%n"); 12 | 13 | for (int i = 1; i <= 20; i++) 14 | { 15 | number = i; 16 | long factorial = 1; // Resets value of factorial after each iteration 17 | for (int j = 1; j <= number; j++) 18 | { 19 | factorial = factorial * j; 20 | } 21 | 22 | System.out.printf("%d\t%d%n", number, factorial); 23 | } // end for loop 24 | } // end method main 25 | } // end class Factorial 26 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.14/Interest.java: -------------------------------------------------------------------------------- 1 | // Modified program of Example 4.6 2 | // @Author: Adam Janecka 3 | package pkg4_14; 4 | 5 | public class Interest { 6 | 7 | public static void main(String[] args) { 8 | 9 | double amount; // amount on deposit at end of each year 10 | double principal = 1000.0; // initial amount before interest 11 | double rate = 5; // interest rate 12 | int counter = 0; 13 | 14 | for (counter = 0; counter <=5; counter++) // Iterates through interest amounts 15 | { 16 | 17 | // display headers 18 | System.out.printf("Interest rate: %.0f%s%n", counter + rate, "%"); 19 | System.out.printf("%s%20s%n", "Year", "Amount on deposit"); 20 | 21 | 22 | // calculate amount on deposit for each of ten years 23 | for (int year = 1; year <= 10; ++year) 24 | { 25 | // calculate new amount for specified year 26 | amount = principal * Math.pow(1.0 + (double)((counter + rate) / 100), year); 27 | 28 | // display the year and the amount 29 | System.out.printf("%4d%,20.2f%n", year, amount); 30 | } 31 | System.out.println(); 32 | 33 | } 34 | } // end method main 35 | } // end class Interest 36 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.16/BarGraph.java: -------------------------------------------------------------------------------- 1 | // Create bar graph of numbers printed by user 2 | // @Author: Adam Janecka 3 | 4 | package pkg4_16; 5 | import java.util.Scanner; 6 | 7 | public class BarGraph { 8 | 9 | public static void main(String[] args) { 10 | 11 | Scanner input = new Scanner(System.in); 12 | 13 | System.out.printf("Enter five integers between 1 and 30 (space-separated),%n" 14 | + "Input a letter to end the program.%n"); 15 | 16 | while(input.hasNextInt()) { // Keeps iterating until a letter is output 17 | 18 | int number = input.nextInt(); 19 | 20 | for(; number > 0; number--) { 21 | System.out.print("*"); 22 | } 23 | 24 | System.out.println(); 25 | } 26 | } // end method main 27 | } // end class BarGraph 28 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.18/Interest.java: -------------------------------------------------------------------------------- 1 | // Modified program of Figure 4.6 2 | // @Author: Adam Janecka 3 | // Note: Outputs are slightly off due to keeping the values as integers 4 | package pkg4_18; 5 | 6 | public class Interest { 7 | 8 | public static void main(String[] args) { 9 | 10 | int amount; // amount on deposit at end of each year 11 | int principal = 100000; // initial amount before interest 12 | double rate = 5; // interest rate 13 | 14 | // display headers 15 | System.out.printf("%s%20s%n", "Year", "Amount on deposit"); 16 | 17 | // calculate amount on deposit for each of ten years 18 | for (int year = 1; year <= 10; ++year) 19 | { 20 | // calculate new amount for specified year 21 | amount = (principal * (100 + 5)) / 100; 22 | principal = amount; 23 | 24 | // display the year and the amount 25 | System.out.printf("%4d%,20d.%d%n", year, amount / 100, amount % 100); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.19/Mystery.java: -------------------------------------------------------------------------------- 1 | // See what the following statements print 2 | 3 | package pkg4_19; 4 | 5 | public class Mystery { 6 | 7 | public static void main(String[] args) { 8 | 9 | int i = 1; 10 | int j = 2; 11 | int k = 3; 12 | int m = 2; 13 | 14 | System.out.println(i == 1); 15 | System.out.println(j == 3); 16 | System.out.println((i >= 1) && (j < 4)); 17 | System.out.println((m <= 99) & (k < m)); 18 | System.out.println((j >= i) || (k == m)); 19 | System.out.println((k + m < j) | (3 - j >= k)); 20 | System.out.println(!(k > m)); 21 | } // end method main 22 | } // end class Mystery 23 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.21/PythagoreanTriples.java: -------------------------------------------------------------------------------- 1 | // Find all Pythagorean triples from 1 to 500 2 | // @Author: Adam Janecka 3 | package pkg4_21; 4 | 5 | public class PythagoreanTriples { 6 | 7 | public static void main(String[] args) { 8 | 9 | System.out.println("Pythagorean triples: "); 10 | 11 | for (int side1 = 1; side1 <= 500; side1++) // first side 12 | { 13 | for (int side2 = 1; side2 <= 500; side2++) // second side 14 | { 15 | for (int hypotenuse = 1; hypotenuse <= 500; hypotenuse++) // hypotenuse 16 | { 17 | // If statement created to avoid duplicate triples 18 | if ((side1 * side1 + side2 * side2) == (hypotenuse * hypotenuse) && (side1 < side2)) 19 | System.out.printf("%d\t%d\t%d%n", side1, side2, hypotenuse); 20 | } 21 | } 22 | } // end for loop 23 | } // end method main 24 | } // end class PythagoreanTriples 25 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.22/Asterisk2.java: -------------------------------------------------------------------------------- 1 | // Modify Exercise 4.15 to display across one set of lines 2 | // @Author: Adam Janecka 3 | package pkg4_22; 4 | 5 | public class Asterisk2 { 6 | 7 | public static void main(String[] args) { 8 | 9 | for (int i = 1; i <= 10; i++) 10 | { 11 | // First Asterisk Design 12 | for (int j = 1; j <= i; j++) 13 | System.out.print("*"); 14 | for (int j = 10; j > i; j--) 15 | System.out.print(" "); 16 | 17 | System.out.print(" "); // Space between designs 18 | 19 | // Second Asterisk Design 20 | for (int j = 10; j >= i; j--) 21 | System.out.print("*"); 22 | for (int j = 1; j < i; j++) 23 | System.out.print(" "); 24 | 25 | System.out.print(" "); 26 | 27 | // Third Asterisk Design 28 | for (int j = 1; j < i; j++) 29 | System.out.print(" "); 30 | for (int j = 10; j >= i; j--) 31 | System.out.print("*"); 32 | 33 | System.out.print(" "); 34 | 35 | // Fourth Asterisk Design 36 | for (int j = 10; j > i; j--) 37 | System.out.print(" "); 38 | for (int j = 1; j <= i; j++) 39 | System.out.print("*"); 40 | 41 | System.out.println(); 42 | } 43 | } // end method main 44 | } // end class Asterisk2 45 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.23/DeMorgan.java: -------------------------------------------------------------------------------- 1 | // Show that two expression are equivalent 2 | // @Author: Adam Janecka 3 | package pkg4_23; 4 | 5 | public class DeMorgan { 6 | 7 | public static void main(String[] args) { 8 | 9 | int x = 5; // All values are 5 to test expression 10 | int y = 5; 11 | int a = 5; 12 | int b = 5; 13 | int g = 5; 14 | int i = 5; 15 | int j = 5; 16 | 17 | System.out.println("All variables have value of 5 to compare expressions.\n"); 18 | 19 | // Exercise a) 20 | System.out.println("Exercise A"); 21 | System.out.printf("!(x < 5) && !(y >= 7):\t\t%b%n", !(x < 5) && !(y >= 7)); 22 | System.out.printf("(x >= 5) || (y < 7):\t\t%b%n%n", (x >= 5) || (y < 7)); 23 | 24 | // Exercise b) 25 | System.out.println("Exercise B"); 26 | System.out.printf("!(a == b) || !(g != 5):\t\t%b%n", !(a == b) || !(g != 5)); 27 | System.out.printf("!((a == b) && (g != 5)):\t%b%n%n", !((a == b) && (g != 5))); 28 | 29 | // Exercise c) 30 | System.out.println("Exercise C"); 31 | System.out.printf("!((x <= 8) && (y > 4)):\t\t%b%n", !((x <= 8) && (y > 4))); 32 | System.out.printf("!(x <= 8) || !(y > 4):\t\t%b%n%n", !(x <= 8) || !(y > 4)); 33 | 34 | // Exercise d) 35 | System.out.println("Exercise D"); 36 | System.out.printf("!((i > 4) || (j <= 6)):\t\t%b%n", !((i > 4) || (j <= 6))); 37 | System.out.printf("!( i > 4) && !(j < = 6):\t%b%n", !(i > 4) && !(j <= 6)); 38 | } // end method main 39 | } // end class DeMorgan 40 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.24/Asterisk3.java: -------------------------------------------------------------------------------- 1 | // Create diamond asterisk pattern 2 | // @Author: Adam Janecka 3 | package pkg4_24; 4 | 5 | public class Asterisk3 { 6 | 7 | public static void main(String[] args) { 8 | 9 | for (int i = 1; i <= 5; i++) // Top half of diamond 10 | { 11 | for (int j = 4; j >= i; j--) 12 | System.out.print(" "); 13 | for (int j = 1; j <= i; j++) 14 | System.out.print("*"); 15 | for (int j = 1; j < i; j++) 16 | System.out.print("*"); 17 | System.out.println(); 18 | } 19 | 20 | for (int i = 1; i <= 4; i++) // Bottom half of diamond 21 | { 22 | for (int j = 1; j <= i; j++) 23 | System.out.print(" "); 24 | for (int j = 5; j > i; j--) 25 | System.out.print("*"); 26 | for (int j = 4; j > i; j--) 27 | System.out.print("*"); 28 | 29 | System.out.println(); 30 | } 31 | 32 | } // end method main 33 | } // end class Asterisk3 34 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.26/BreakSubstitute.java: -------------------------------------------------------------------------------- 1 | // Show a replacement for the break statement 2 | // @Author: Adam Janecka 3 | package pkg4_26; 4 | 5 | public class BreakSubstitute { 6 | 7 | public static void main(String[] args) { 8 | 9 | int x = 0; // variable used to exit break 10 | int count = 1; 11 | 12 | for (count = 1; (count <= 10) && (x < 1); count++) 13 | { 14 | if (count == 5) 15 | ++x; // equivalent of break statement 16 | System.out.printf("%d ", count); 17 | } 18 | System.out.println(); 19 | } // end method main 20 | } // end class BreakSubstitute 21 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.27/Mystery2.java: -------------------------------------------------------------------------------- 1 | // What does the following code print? 2 | package pkg4_27; 3 | 4 | public class Mystery2 { 5 | 6 | public static void main(String[] args) { 7 | 8 | for (int i = 1; i <= 5; i++) 9 | { 10 | for (int j = 1; j <= 3; j++) 11 | { 12 | for (int k = 1; k <= 4; k++) 13 | System.out.print('*'); 14 | System.out.println(); 15 | } // end inner for 16 | } // end outer for 17 | } // end method main 18 | } // end class Mystery2 19 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.28/ContinueSubstitute.java: -------------------------------------------------------------------------------- 1 | // Provide substite for continue statement 2 | // @Author: Adam Janecka 3 | 4 | package pkg4_28; 5 | 6 | public class ContinueSubstitute { 7 | 8 | public static void main(String[] args) { 9 | 10 | for (int count = 1; count <= 10; count++) // loop 10 times 11 | { 12 | if (count != 5) 13 | System.out.printf("%d ", count); // Continue substitute 14 | } 15 | 16 | System.out.printf("%nUsed continue substitute to skip printing 5%n"); 17 | } // end method main 18 | } // end class ContinueSubstitute 19 | -------------------------------------------------------------------------------- /Chapter04/Exercises/4.32/Facebook.java: -------------------------------------------------------------------------------- 1 | // See how many months it takes Facebook to reach 1.5 billion users 2 | // @Author: Adam Janecka 3 | package pkg4_32; 4 | 5 | public class Facebook { 6 | 7 | public static void main(String[] args) { 8 | 9 | double users = 1; // Number of users in billions 10 | int month = 0; // Number of months since October 2012 11 | 12 | System.out.println("Facebook had 1 billion users in October 2012."); 13 | 14 | for (users = 1; users <= 1.5;) 15 | { 16 | users = users * 1.04; 17 | month++; 18 | } 19 | 20 | System.out.printf("They will achieve 1.5 billion users in %d months%n", month); 21 | } // end method main 22 | } // end class Facebook 23 | -------------------------------------------------------------------------------- /Chapter05/Examples/5.06/RandomIntegers.java: -------------------------------------------------------------------------------- 1 | // Fig. 5.6: RandomIntegers.java 2 | // Shifted and scaled random integers. 3 | package pkg5_06; 4 | import java.security.SecureRandom; // program uses class SecureRandom 5 | 6 | public class RandomIntegers { 7 | 8 | public static void main(String[] args) { 9 | 10 | // randomNumbers object will produce secure random numbers 11 | SecureRandom randomNumbers = new SecureRandom(); 12 | 13 | // loop 20 times 14 | for (int counter = 1; counter <= 20; counter++) 15 | { 16 | // pick random integer from 1 to 6 17 | int face = 1 + randomNumbers.nextInt(6); 18 | 19 | System.out.printf("%d ", face); // display generated value 20 | 21 | // if counter is divisible by 5, start a new line of output 22 | if (counter % 5 == 0) 23 | System.out.println(); 24 | } 25 | } // end method main 26 | } // end class RandomIntegers 27 | -------------------------------------------------------------------------------- /Chapter05/Examples/5.10/MethodOverload.java: -------------------------------------------------------------------------------- 1 | // Fig. 5.10: MethodOverload.java 2 | // Overloaded method declarations. 3 | package pkg5_10; 4 | 5 | public class MethodOverload { 6 | 7 | // test overloaded square methods 8 | public static void main(String[] args) { 9 | 10 | System.out.printf("Square of integer 7 is %d%n", square (7)); 11 | System.out.printf("Square of double 7.5 is %f%n", square(7.5)); 12 | } // end method main 13 | 14 | // square method with int argument 15 | public static int square(int intValue) 16 | { 17 | System.out.printf("%nCalled square with int argument: %d%n", 18 | intValue); 19 | return intValue * intValue; 20 | } // end method intValue 21 | 22 | // square method with a double argument 23 | public static double square (double doubleValue) 24 | { 25 | System.out.printf("%nCalled square with double argument: %f%n", 26 | doubleValue); 27 | return doubleValue * doubleValue; 28 | } // end method square 29 | } // end class MethodOverload 30 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.06/Sphere.java: -------------------------------------------------------------------------------- 1 | // Exercise 5.6: Sphere.java 2 | // Calculate the volume of a sphere 3 | package pkg5_06; 4 | import java.util.Scanner; 5 | 6 | public class Sphere { 7 | 8 | // obtain radius from user and display volume of sphere 9 | public static void main(String[] args) { 10 | 11 | Scanner input = new Scanner(System.in); 12 | 13 | System.out.print("Enter radius of sphere: "); 14 | double radius = input.nextDouble(); 15 | 16 | System.out.printf("Volume is %f%n", sphereVolume(radius)); 17 | } // end method main 18 | 19 | // calculate and return sphere volume 20 | public static double sphereVolume(double radius) 21 | { 22 | double volume = (4.0 / 3.0) * Math.PI * Math.pow(radius, 3); 23 | return volume; 24 | } // end method sphereVolume 25 | } // end class Sphere 26 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.09/Rounding.java: -------------------------------------------------------------------------------- 1 | // Create a program that rounds double values to the nearest integer 2 | // @Author: Adam Janecka 3 | package pkg5_09; 4 | import java.util.Scanner; 5 | 6 | public class Rounding { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | 13 | double number = 0; // Number input by user 14 | double round; // Rounded answer 15 | 16 | System.out.print("Enter decimal number or -1 to quit: "); 17 | number = input.nextDouble(); 18 | 19 | // allows multiple uses 20 | while (number != -1){ 21 | 22 | round = Math.floor(number + 0.5); 23 | System.out.printf("Original Number: %.2f%n" //Prints out answer 24 | + "Rounded Number: %.0f%n", number, round); 25 | 26 | System.out.print("Enter decimal number or -1 to quit: "); 27 | number = input.nextDouble(); 28 | 29 | } 30 | } // end method main 31 | } // end class Rounding 32 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.12/RandomInteger.java: -------------------------------------------------------------------------------- 1 | // Assign random integer between a certain range 2 | // @Author: Adam Janecka 3 | package pkg5_12; 4 | import java.security.SecureRandom; 5 | 6 | public class RandomInteger { 7 | 8 | public static void main(String[] args) { 9 | 10 | SecureRandom random = new SecureRandom(); 11 | 12 | // Part a 13 | int a = 1 + random.nextInt(2); 14 | System.out.printf("Part a) %d%n", a); 15 | 16 | // Part b 17 | int b = 1 + random.nextInt(100); 18 | System.out.printf("Part b) %d%n", b); 19 | 20 | // Part c 21 | int c = random.nextInt(10); 22 | System.out.printf("Part c) %d%n", c); 23 | 24 | // Part d 25 | int d = 1000 + random.nextInt(113); 26 | System.out.printf("Part d) %d%n", d); 27 | 28 | // Part e 29 | int e = random.nextInt(3) - 1; 30 | System.out.printf("Part e) %d%n", e); 31 | 32 | // Part f 33 | int f = random.nextInt(15) - 3; 34 | System.out.printf("Part f) %d%n", f); 35 | } // end method main 36 | } // end class RandomInteger 37 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.13/RandomInteger2.java: -------------------------------------------------------------------------------- 1 | // Assign statements that will display random numbers 2 | // @Author: Adam Janecka 3 | package pkg5_13; 4 | import java.security.SecureRandom; 5 | 6 | public class RandomInteger2 { 7 | 8 | public static void main(String[] args) { 9 | 10 | SecureRandom random = new SecureRandom(); 11 | 12 | // Part a) 13 | int a = 2 * (1 + random.nextInt(5)); 14 | System.out.printf("Part a) %d%n", a); 15 | 16 | // Part b) 17 | int b = 1 + 2 * (1 + random.nextInt(5)); 18 | System.out.printf("Part b) %d%n", b); 19 | 20 | // Part c) 21 | int c = 2 + 4 * (1 + random.nextInt(5)); 22 | System.out.printf("Part c) %d%n", c); 23 | } // end method main 24 | } // end class RandomInteger2 25 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.14/Exponentiation.java: -------------------------------------------------------------------------------- 1 | // Write a method equal to Math.pow(); 2 | // @Author: Adam Janecka 3 | package pkg5_14; 4 | import java.util.Scanner; 5 | 6 | public class Exponentiation { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | int base = 0; // Base value 13 | int exponent = 0; // Exponent value 14 | 15 | System.out.print("Enter base or -1 to quit: "); 16 | base = input.nextInt(); 17 | 18 | while (base != 0) // Allows multiple uses of program 19 | { 20 | System.out.print("Enter exponent: "); 21 | exponent = input.nextInt(); 22 | 23 | System.out.printf("%d^%d = %d%n", base, exponent, integerPower(base, exponent)); 24 | 25 | System.out.print("Enter base or -1 to quit: "); 26 | base = input.nextInt(); 27 | } 28 | } // end method main 29 | 30 | // Calculates the exponential value of two numbers 31 | public static int integerPower(int base, int exponent) 32 | { 33 | int result = 1; 34 | 35 | for (int i = 1; i <= exponent; i++) 36 | { 37 | result *= base; 38 | } 39 | 40 | return result; 41 | } // end method integerPower 42 | } //end class Exponentiation 43 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.15/Hypotenuse.java: -------------------------------------------------------------------------------- 1 | // Find the hypotenuse given two sides of a triangle 2 | // @Author: Adam Janecka 3 | package pkg5_15; 4 | import java.util.Scanner; 5 | 6 | public class Hypotenuse { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | double side1; // First side of triangle 13 | double side2; // Second side of triangle 14 | double hypotenuse; // Hypotenuse 15 | 16 | System.out.print("Enter first side of triangle: "); 17 | side1 = input.nextDouble(); 18 | System.out.print("Enter second side of triangle: "); 19 | side2 = input.nextDouble(); 20 | 21 | System.out.printf("Hypotenuse is %.2f%n", hypotenuse(side1, side2)); 22 | } // end method main 23 | 24 | // Finds the hypotenuse 25 | public static double hypotenuse(double side1, double side2) 26 | { 27 | double x = side1 * side1; // Side 1 squared 28 | double y = side2 * side2; // Side 2 squared 29 | 30 | double hypotenuse = Math.sqrt(x + y); 31 | 32 | return hypotenuse; 33 | } // end method hypotenuse 34 | } // end class Hypotenuse 35 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.16/Multiples.java: -------------------------------------------------------------------------------- 1 | // See if one number is a multiple of another 2 | // @Author: Adam Janecka 3 | package pkg5_16; 4 | import java.util.Scanner; 5 | 6 | // See if one number is a multiple of another 7 | // @Author: Adam Janecka 8 | package pkg5_16; 9 | import java.util.Scanner; 10 | 11 | public class Multiples { 12 | 13 | public static void main(String[] args) { 14 | 15 | Scanner input = new Scanner(System.in); 16 | 17 | int num1; // First number 18 | int num2; // Second number 19 | 20 | System.out.print("Enter a pair of numbers or -1 to quit: "); 21 | while(!input.hasNext ("-1")) // While the number is not -1 22 | { 23 | num1 = input.nextInt(); 24 | num2 = input.nextInt(); 25 | 26 | if (isMultiple(num1, num2)) 27 | System.out.printf("%d is a multiple of %d.%n", num2, num1); 28 | else 29 | System.out.printf("%d is not a multiple of %d.%n", num2, num1); 30 | } 31 | } // end method main 32 | 33 | // Sees if a number is a multiple of another 34 | public static boolean isMultiple(int num1, int num2) 35 | { 36 | if (num2 % num1 == 0) 37 | return true; 38 | else 39 | return false; 40 | } // end method isMultiple 41 | } // end class Multiples 42 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.17/EvenOdd.java: -------------------------------------------------------------------------------- 1 | // See if a function is even or odd using a method 2 | // @Author: Adam Janecka 3 | package pkg5_17; 4 | import java.util.Scanner; 5 | 6 | public class EvenOdd { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | int number = 0; // Number input by user 13 | 14 | System.out.print("Enter a string of numbers or -1 to quit: "); 15 | 16 | 17 | while (!input.hasNext("-1")) // while the next number is not -1 18 | { 19 | number = input.nextInt(); 20 | 21 | if (isEven(number)) // if the number is even 22 | System.out.printf("%d is even.%n", number); 23 | else // if the number is odd 24 | System.out.printf("%d is odd.%n", number); 25 | 26 | } 27 | } // end method main 28 | 29 | // Sees if a number is even or odd 30 | public static boolean isEven(int number) 31 | { 32 | if (number % 2 == 0) // If number is even 33 | return true; 34 | else // If number is odd 35 | return false; 36 | } // end method isEven 37 | } // end class EvenOdd 38 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.18/Asterisk.java: -------------------------------------------------------------------------------- 1 | // Create a square of asterisks 2 | // @Author: Adam Janecka 3 | package pkg5_18; 4 | import java.util.Scanner; 5 | 6 | public class Asterisk { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | int side; // Side of the asterisk square 13 | 14 | System.out.print("Enter length of the side of the square: "); 15 | side = input.nextInt(); 16 | 17 | squareofAsterisks(side); 18 | } // end method main 19 | 20 | // Prints a square of asterisks 21 | public static void squareofAsterisks(int side) 22 | { 23 | for (int i = 1; i <= side; i++) 24 | { 25 | for (int j = 1; j <= side; j++) 26 | System.out.printf("*"); 27 | System.out.println(); 28 | } 29 | 30 | } // end method squareofAsterisks 31 | } // end class Asterisk 32 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.19/CharacterSquare.java: -------------------------------------------------------------------------------- 1 | // Create a square of a certain character 2 | // @Author: Adam Janecka 3 | package pkg5_19; 4 | import java.util.Scanner; 5 | 6 | public class CharacterSquare { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | int side; // length of the side 13 | char x; // The character input by user 14 | 15 | System.out.print("Enter length of side: "); 16 | side = input.nextInt(); 17 | System.out.print("Enter character: "); 18 | x = input.next().charAt(0); 19 | 20 | CharSquare(side, x); 21 | } // end method main 22 | 23 | // Prints out a square of the ceratin character 24 | public static void CharSquare(int side, char x) 25 | { 26 | for (int i = 1; i <= side; i++) 27 | { 28 | for (int j = 1; j<= side; j++) 29 | System.out.printf("%s", x); 30 | System.out.println(); 31 | } 32 | } // end method CharSquare 33 | } // end class CharacterSquare 34 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.20/CircleArea.java: -------------------------------------------------------------------------------- 1 | // Finds the area of a circle 2 | // @Author: Adam Janecka 3 | package pkg5_20; 4 | import java.util.Scanner; 5 | 6 | public class CircleArea { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | double radius; // The radius of the circle 12 | 13 | System.out.print("Enter radius: "); 14 | radius = input.nextDouble(); 15 | 16 | double area = circleArea(radius); 17 | System.out.printf("The area is %.2f%n", area); 18 | } // end method main 19 | 20 | // Calculates the area of a circle 21 | public static double circleArea(double radius) 22 | { 23 | double area = Math.PI * Math.pow(radius, 2); 24 | return area; 25 | } // end method circleArea 26 | } // end class CircleArea 27 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.22/Temperature.java: -------------------------------------------------------------------------------- 1 | // Converts temperature from Celsius to Fahrenheit and vice versa 2 | // @Author: Adam Janecka 3 | package pkg5_22; 4 | import java.util.Scanner; 5 | 6 | public class Temperature { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | double temp; // The temperature input by user 12 | 13 | // Converts from Fahrenheit to Celsius 14 | System.out.print("Enter temperature in Fahrenheit: "); 15 | temp = input.nextDouble(); 16 | System.out.printf("The temperature in Celcius is %.2f%n", celsius(temp)); 17 | 18 | // Converts from Celsius to Fahrenheit 19 | System.out.print("Enter temperature in Celcius: "); 20 | temp = input.nextDouble(); 21 | System.out.printf("The temperature in Fahrenheit is %.2f%n", fahrenheit(temp)); 22 | } // end method main 23 | 24 | // Converts from Fahrenheit to Celsius 25 | public static double celsius (double fahrenheit) 26 | { 27 | double celsius = 5.0 / 9.0 * (fahrenheit - 32); 28 | return celsius; 29 | } // end method celsius 30 | 31 | // Converts from Celsius to Fahrenheit 32 | public static double fahrenheit(double celsius) 33 | { 34 | double fahrenheit = 9.0 / 5.0 * celsius + 32; 35 | return fahrenheit; 36 | } // end method fahrenheit 37 | } // end class Temperature 38 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.23/Minimum.java: -------------------------------------------------------------------------------- 1 | // Finds the minimum of three numbers 2 | // @Author: Adam Janecka 3 | package pkg5_23; 4 | import java.util.Scanner; 5 | 6 | public class Minimum { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int num1; // First number 12 | int num2; // Second number 13 | int num3; // Third number 14 | 15 | System.out.print("Enter first number: "); 16 | num1 = input.nextInt(); 17 | System.out.print("Enter second number: "); 18 | num2 = input.nextInt(); 19 | System.out.print("Enter third number: "); 20 | num3 = input.nextInt(); 21 | 22 | System.out.printf("The smallest number is %d%n", minimum3(num1, num2, num3)); 23 | } // end method main 24 | 25 | // Finds the minimum of 3 numbers 26 | public static int minimum3(int num1, int num2, int num3) 27 | { 28 | int smallest = num1; 29 | 30 | if (num2 < smallest) 31 | smallest = num2; 32 | if (num3 < smallest) 33 | smallest = num3; 34 | 35 | return smallest; 36 | } // end method minimum3 37 | } // end class Minimum 38 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.24/PerfectNumbers.java: -------------------------------------------------------------------------------- 1 | // Prints out all the perfect numbers from 1 to 1000 and their factors 2 | // @Author: Adam Janecka 3 | package pkg5_24; 4 | 5 | public class PerfectNumbers { 6 | 7 | public static void main(String[] args) { 8 | 9 | System.out.printf("Perfect numbers are: %n"); 10 | 11 | for (int num = 1; num <= 1000; num++) 12 | { 13 | if (isPerfect(num)) 14 | { 15 | System.out.printf("%d: ", num); 16 | printFactors(num); 17 | System.out.println(); 18 | } 19 | } 20 | } // end method main 21 | 22 | // Sees if the number is a perfect number 23 | public static boolean isPerfect(int number) 24 | { 25 | int sum = 0; // The sum off all the factors 26 | 27 | for (int i = 1; i < number; i++) 28 | { 29 | if (number % i == 0) 30 | sum += i; 31 | } 32 | 33 | if (sum == number) 34 | return true; 35 | else 36 | return false; 37 | } // end method isPerfect 38 | 39 | // Prints out the factors of the perfect numbers 40 | public static void printFactors(int num) 41 | { 42 | for (int i = 1; i < num; i++) 43 | { 44 | if (num % i == 0) 45 | System.out.printf("%d ", i); 46 | } 47 | } // end method printFactors 48 | } // end class PerfectNumbers 49 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.25/Prime.java: -------------------------------------------------------------------------------- 1 | // Find all the prime numbers from 1 to 10,000 2 | // @Author: Adam Janecka 3 | package pkg5_25; 4 | 5 | public class Prime { 6 | 7 | public static void main(String[] args) { 8 | 9 | for (int num = 1; num <= 10000; num++) 10 | { 11 | if (sqrtPrime(num)) 12 | System.out.printf("%d is prime.%n", num); 13 | } 14 | } // end method main 15 | 16 | // Finds out if the number is prime 17 | public static boolean isPrime(int num) 18 | { 19 | for (int i = 2; i <= num / 2; i++) 20 | { 21 | if (num % i == 0) 22 | return false; 23 | } 24 | 25 | return true; 26 | } // end method isPrime 27 | 28 | // Finds out if the number is prime using square root 29 | public static boolean sqrtPrime(int num) 30 | { 31 | for (int i = 2; i <= Math.sqrt(num); i++) 32 | { 33 | if (num % i == 0) 34 | return false; 35 | } 36 | 37 | return true; 38 | } 39 | } // end class Prime 40 | 41 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.26/ReverseDigits.java: -------------------------------------------------------------------------------- 1 | // Reverses the digits in a number 2 | // @Author: Adam Janecka 3 | package pkg5_26; 4 | import java.util.Scanner; 5 | 6 | public class ReverseDigits { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int num; // Number input by user 12 | 13 | System.out.print("Enter number: "); 14 | num = input.nextInt(); 15 | 16 | System.out.print("Number reversed is "); 17 | reverseDigits(num); 18 | System.out.println(); 19 | } // end method main 20 | 21 | // Reverses the digits in the number 22 | public static void reverseDigits(int number) 23 | { 24 | while (number > 0) 25 | { 26 | System.out.printf("%d", number % 10); 27 | number = number / 10; 28 | } 29 | } // end method reverseDigits 30 | } // end class ReverseDigits 31 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.27/GreatestCommonFactor.java: -------------------------------------------------------------------------------- 1 | // Finds the greatest common divisor of two integers 2 | // @Author: Adam Janecka 3 | package pkg5_27; 4 | import java.util.Scanner; 5 | 6 | public class GreatestCommonFactor { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int num1; // First number 12 | int num2; // Second number 13 | 14 | System.out.print("Enter first number: "); 15 | num1 = input.nextInt(); 16 | System.out.print("Enter second number: "); 17 | num2 = input.nextInt(); 18 | int divisor = gcd(num1, num2); 19 | 20 | System.out.printf("The greatest common divisor is %d%n", divisor); 21 | } // end method main 22 | 23 | // Finds the greatest common divisor of two numbers 24 | public static int gcd(int num1, int num2) 25 | { 26 | 27 | int divisor = 1; // Every two numbers share a factor of 1 28 | 29 | for (int i = 1; i <= num1; i++) 30 | { 31 | if (num1 % i == 0 && num2 % i == 0) 32 | divisor = i; 33 | } 34 | 35 | return divisor; 36 | } // end method gcd 37 | } // end class GreatestCommonFactor 38 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.28/GradeAverage.java: -------------------------------------------------------------------------------- 1 | // Outputs quality points based on user's average 2 | // @Author: Adam Janecka 3 | package pkg5_28; 4 | import java.util.Scanner; 5 | 6 | public class GradeAverage { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | int average; // Average of grades input by user 12 | 13 | System.out.print("Enter grade average bewteen 1 and 100: "); 14 | average = input.nextInt(); 15 | 16 | int points = qualityPoints(average); 17 | System.out.printf("Quality Points: %d%n", points); 18 | } // end method main 19 | 20 | // Finds out the number of quality points 21 | public static int qualityPoints(int average) 22 | { 23 | int points; 24 | 25 | if (average < 60) 26 | points = 0; 27 | else if (average < 70) 28 | points = 1; 29 | else if (average < 80) 30 | points = 2; 31 | else if (average < 90) 32 | points = 3; 33 | else 34 | points = 4; 35 | 36 | return points; 37 | } // end method qualityPoints 38 | } // end class GradeAverage 39 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.30/GuessNumber.java: -------------------------------------------------------------------------------- 1 | // Has the user guess a number between 1 and 1000 2 | // @Author: Adam Janecka 3 | package pkg5_30; 4 | import java.util.Scanner; 5 | import java.security.SecureRandom; 6 | 7 | public class GuessNumber { 8 | 9 | public static void main(String[] args) { 10 | 11 | Scanner input = new Scanner(System.in); 12 | SecureRandom random = new SecureRandom(); 13 | int guess = 0; // Number guessed by user 14 | int count = 1; 15 | 16 | 17 | 18 | while (count == 1) // Allows multiple repetitions of the problem 19 | { 20 | System.out.print("Guess the number: "); 21 | guess = input.nextInt(); 22 | 23 | int num = 1 + random.nextInt(1000); // Acquires a number at random 24 | 25 | while (guess != num) 26 | { 27 | 28 | if (guess < num) 29 | System.out.println("Too low."); 30 | if (guess > num) 31 | System.out.println("Too high."); 32 | guess = input.nextInt(); 33 | 34 | } 35 | 36 | System.out.println("Congratulations. You guessed the number! " 37 | + "Enter 1 to play again or 2 to quit: "); 38 | count = input.nextInt(); 39 | } 40 | } // end method main 41 | } // end class GuessNumber 42 | -------------------------------------------------------------------------------- /Chapter05/Exercises/5.32/Distance.java: -------------------------------------------------------------------------------- 1 | // Finds the distance between two points 2 | // @Author: Adam Janecka 3 | package pkg5_32; 4 | import java.util.Scanner; 5 | 6 | public class Distance { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | int x1; // X value of first point 13 | int y1; // Y value of first point 14 | int x2; // X value of second point 15 | int y2; // Y value of second point 16 | 17 | System.out.print("Enter x value of first point: "); 18 | x1 = input.nextInt(); 19 | System.out.print("Enter y value of first point: "); 20 | y1 = input.nextInt(); 21 | System.out.print("Enter x value of second point: "); 22 | x2 = input.nextInt(); 23 | System.out.print("Enter y value of secon point: "); 24 | y2 = input.nextInt(); 25 | 26 | double distance = distance(x1, y1, x2, y2); 27 | 28 | System.out.printf("Distance between points is %.2f%n", distance); 29 | } // end method main 30 | 31 | // Calculates the distance between two points 32 | public static double distance(int x1, int y1, int x2, int y2) 33 | { 34 | double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); 35 | return distance; 36 | } // end method distance 37 | } // end class Distance 38 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.02/InitArray.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.2 : InitArray.java 2 | // Initializing the elements of an array to default values of zero. 3 | package pkg6_02; 4 | 5 | public class InitArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | // declare variable array and initialize it with array object 10 | int[] array = new int[10]; // create the array object 11 | 12 | System.out.printf("%s%8s%n", "Index", "Value"); // column headings 13 | 14 | // output each array element's value 15 | for (int counter = 0; counter < array.length; counter++) 16 | System.out.printf("%5d%8d%n", counter, array[counter]); 17 | 18 | } // end metho main 19 | } // end class InitArray 20 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.03/InitArray.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.3: InitArray.java 2 | // Initializing the elements of an array with an array initializer 3 | package pkg6_03; 4 | 5 | public class InitArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | // initializer list specifies the initial value for each element 10 | int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60, 37}; 11 | 12 | System.out.printf("%s%8s%n", "Inex", "Value"); // column headings 13 | 14 | // output each array element's value 15 | for (int counter = 0; counter < array.length; counter++) 16 | System.out.printf("%5d%8d%n", counter, array[counter]); 17 | } // end method main 18 | } // end class InitArray 19 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.04/InitArray.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.4: InitArray.java 2 | // Calculating the values to be placed into the elements of an array. 3 | package pkg6_04; 4 | 5 | public class InitArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | final int ARRAY_LENGTH = 10; // declare constant 10 | int[] array = new int[ARRAY_LENGTH]; 11 | 12 | // calculate value for each array element 13 | for(int counter = 0; counter < array.length; counter++) 14 | array[counter] = 2 + 2 * counter; 15 | 16 | System.out.printf("%s%8s%n", "Index", "Value"); // column headings 17 | 18 | // output each array element's value 19 | for (int counter = 0; counter < array.length; counter++) 20 | System.out.printf("%5d%8d%n", counter, array[counter]); 21 | } // end method main 22 | } // end class InitArray 23 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.05/SumArray.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.5: SumArray.java 2 | // Computing the sum of the elements of an array. 3 | package pkg6_05; 4 | 5 | public class SumArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; 10 | int total = 0; 11 | 12 | // add each element's value to total 13 | for (int counter = 0; counter < array.length; counter++) 14 | total += array[counter]; 15 | 16 | System.out.printf("Total of array elements: %d%n", total); 17 | } // end method main 18 | } // end class SumArray 19 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.06/BarChart.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.6: BarChart.java 2 | // Bar chart printing program 3 | package pkg6_06; 4 | 5 | public class BarChart { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] array = {0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1}; 10 | 11 | System.out.println("Grade distribution: "); 12 | 13 | // for each array element, output a bar of the chart 14 | for (int counter = 0; counter < array.length; counter++) 15 | { 16 | // output bar label ("00-09: ", ..., "90-99: ", "100: ") 17 | if (counter == 10) 18 | System.out.printf("%5d: ", 100); 19 | else 20 | System.out.printf("%02d-%02d: ", 21 | counter * 10, counter * 10 + 9); 22 | 23 | // print bar of asterisks 24 | for (int stars = 0; stars < array[counter]; stars++) 25 | System.out.print("*"); 26 | 27 | System.out.println(); 28 | } 29 | } // end method main 30 | } // end class BarChart 31 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.07/RollDie.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.7: RollDie.java 2 | // Die-rolling program using arrays instead of switch. 3 | package pkg6_07; 4 | import java.security.SecureRandom; 5 | 6 | public class RollDie { 7 | 8 | public static void main(String[] args) { 9 | 10 | SecureRandom randomNumbers = new SecureRandom(); 11 | int[] frequency = new int[7]; // array of frequency counters 12 | 13 | // roll die 6,000,000 times; use die value as frequency index 14 | for (int roll = 1; roll <= 6000000; roll++) 15 | ++frequency[1 + randomNumbers.nextInt(6)]; 16 | 17 | System.out.printf("%s%10s%n", "Face", "Frequency"); 18 | 19 | // output each array element's value 20 | for (int face = 1; face < frequency.length; face++) 21 | System.out.printf("%4d%10d%n", face, frequency[face]); 22 | } // end method main 23 | } // end class RollDie 24 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.09/EnhancedForTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.9: EnhancedForTest.java 2 | // Using the enhanced for statement to total integers in an array 3 | package pkg6_09; 4 | 5 | public class EnhancedForTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; 10 | int total = 0; 11 | 12 | // add each element's value to total 13 | for (int number: array) 14 | total += number; 15 | 16 | System.out.printf("Total of array elements: %d%n", total); 17 | } // end method main 18 | } // end class EnhancedForTest 19 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.12/InitArray.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.12: InitArray.java 2 | // Initializinig two-dimensional arrays 3 | package pkg6_12; 4 | 5 | public class InitArray { 6 | 7 | // create and output two-dimensional arrays 8 | public static void main(String[] args) { 9 | 10 | int[][] array1 = {{1, 2, 3}, {4, 5, 6}}; 11 | int[][] array2 = {{1, 2}, {3}, {4, 5, 6}}; 12 | 13 | System.out.println("Values in array1 by row are"); 14 | outputArray(array1); // displays array1 by row 15 | 16 | System.out.printf("%nValues in array2 by row are%n"); 17 | outputArray(array2); // displays array2 by row 18 | } // end method main 19 | 20 | // output rows and columns of a two-dimensional array 21 | public static void outputArray(int[][] array) 22 | { 23 | // loop through array's rows 24 | for (int row = 0; row < array.length; row++) 25 | { 26 | // loop through columns of current row 27 | for (int column = 0; column < array[row].length; column++) 28 | System.out.printf("%d ", array[row][column]); 29 | 30 | System.out.println(); 31 | } 32 | } // end method outputArray 33 | } // end class InitArray 34 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.13/VarargsTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 6.13: VarargsTest.java 2 | // Using variable-length argument lists. 3 | package pkg6_13; 4 | 5 | public class VarargsTest { 6 | 7 | // calculate average 8 | public static double average(double... numbers) 9 | { 10 | double total = 0.0; 11 | 12 | // calculate total using the enhanced for statement 13 | for (double d : numbers) 14 | total += d; 15 | 16 | return total / numbers.length; 17 | } // end method average 18 | 19 | public static void main(String[] args) { 20 | 21 | double d1 = 10.0; 22 | double d2 = 20.0; 23 | double d3 = 30.0; 24 | double d4 = 40.0; 25 | 26 | System.out.printf("d1 = %.1f%nd2 = %.1f%nd3 = %.1f%nd4 = %.1f%n%n", 27 | d1, d2, d3, d4); 28 | 29 | System.out.printf("Average of d1 an d2 is %.1f%n", 30 | average(d1, d2)); 31 | System.out.printf("Average of d1, d2 and d3 is %.1f%n", 32 | average(d1, d2, d3)); 33 | System.out.printf("Average of d1, d2, d3 and d4 is %.1f%n", 34 | average(d1, d2, d3, d4)); 35 | } // end method main 36 | } // end class VarargsTest 37 | -------------------------------------------------------------------------------- /Chapter06/Examples/6.14/InitArray.java: -------------------------------------------------------------------------------- 1 | // Fig 6.14: InitArray.java 2 | // Initializing an array using command-line arguments 3 | package pkg6_14; 4 | 5 | public class InitArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | // check number of command-line arguments 10 | if (args.length != 3) 11 | System.out.printf( 12 | "Error: Please re-enter the entire command, including%n" 13 | + "an array size, initial value and increment.%n"); 14 | 15 | else 16 | { 17 | // get array size from first comman-line argument 18 | int arrayLength = Integer.parseInt(args[0]); 19 | int[] array = new int[arrayLength]; 20 | 21 | // get initial value and increment from command-line arguments 22 | int initialValue = Integer.parseInt(args[1]); 23 | int increment = Integer.parseInt(args[2]); 24 | 25 | // calculate value for each array element 26 | for (int counter = 0; counter < array.length; counter++) 27 | array[counter] = initialValue + increment * counter; 28 | 29 | System.out.printf("%s%8s%n", "Index", "Value"); 30 | 31 | // display array index and value 32 | for (int counter = 0; counter < array.length; counter++) 33 | System.out.printf("%5d%8d%n", counter, array[counter]); 34 | } 35 | } // end method main 36 | } // end class InitArray 37 | -------------------------------------------------------------------------------- /Chapter06/Exercises/6.14/VariableProduct.java: -------------------------------------------------------------------------------- 1 | // Calculates the product of a variable number of arguments 2 | // @Author: Adam Janecka 3 | package pkg6_14; 4 | 5 | public class VariableProduct { 6 | 7 | public static void main(String[] args) { 8 | 9 | double num1 = 12.5; 10 | double num2 = 5; 11 | double num3 = 7.5; 12 | double num4 = 6.6; 13 | 14 | System.out.print("Num1 = 12.5\n" 15 | + "Num2 = 5\n" 16 | + "Num3 = 7.5\n" 17 | + "Num4 = 6.6\n"); 18 | 19 | System.out.printf("Num1 * Num2 = %.2f%n", product(num1, num2)); 20 | System.out.printf("Num1 * Num2 * Num3 = %.2f%n", product(num1, num2, num3)); 21 | System.out.printf("Num1 * Num2 * Num4 = %.2f%n", product(num1, num2, num4)); 22 | } // end method main 23 | 24 | // Calculates the product of a variable number of integers 25 | public static double product(double... numbers) 26 | { 27 | double product = 1; 28 | 29 | // Calculates the product of all numbers 30 | for (int i = 0; i < numbers.length; i++) 31 | product *= numbers[i]; 32 | 33 | return product; 34 | } // end method product 35 | } // end class VariableProduct 36 | -------------------------------------------------------------------------------- /Chapter06/Exercises/6.15/CommandLine.java: -------------------------------------------------------------------------------- 1 | // Rewrite Figure 6.2 to have command-line argument 2 | // @Author: Adam Janecka 3 | package pkg6_15; 4 | 5 | public class CommandLine { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] array; 10 | if (args.length != 0) 11 | { 12 | int arrayLength = Integer.parseInt(args[0]); 13 | array = new int[arrayLength]; 14 | } 15 | else 16 | { 17 | System.out.print("No command-line argument. \n"); 18 | array = new int[10]; 19 | } 20 | 21 | // declare variable array and initialize it with array object 22 | System.out.printf("%s%8s%n", "Index", "Value"); // column headings 23 | 24 | // output each array element's value 25 | for (int counter = 0; counter < array.length; counter++) 26 | System.out.printf("%5d%8d%n", counter, array[counter]); 27 | 28 | } // end method main 29 | } // end class CommandLine 30 | -------------------------------------------------------------------------------- /Chapter06/Exercises/6.16/EnhancedFor.java: -------------------------------------------------------------------------------- 1 | // Calculate the sum of arguments from the command line 2 | // @Author: Adam Janecka 3 | package pkg6_16; 4 | 5 | public class EnhancedFor { 6 | 7 | public static void main(String[] args) { 8 | 9 | if(args.length == 0) 10 | System.out.print("No arguments input.\n"); 11 | else 12 | { 13 | double total = 0.0; 14 | 15 | for (String s : args) 16 | { 17 | double d = Double.parseDouble(s); // Turn argument into double value 18 | total += d; 19 | } 20 | System.out.printf("Sum: %.2f\n", total); 21 | } 22 | } // end method main 23 | } // end class EnhancedFor 24 | -------------------------------------------------------------------------------- /Chapter06/Exercises/6.17/DiceSum.java: -------------------------------------------------------------------------------- 1 | // Calculate the sum of two dice rolls 36,000,000 times 2 | // @Author: Adam Janecka 3 | package pkg6_17; 4 | import java.security.SecureRandom; 5 | 6 | public class DiceSum { 7 | 8 | public static void main(String[] args) { 9 | 10 | SecureRandom random = new SecureRandom(); 11 | int[] sumCount = new int[13]; // Stores the number of times each sum appears 12 | int sum; // Sum of two dice 13 | 14 | // Rolls dice 36,000,000 times 15 | for (int i = 0; i < 36000000; i++) 16 | { 17 | // Get two dice values 18 | int dice1 = 1 + random.nextInt(6); 19 | int dice2 = 1 + random.nextInt(6); 20 | sum = dice1 + dice2; 21 | sumCount[sum]++; // Add one to sum count 22 | } 23 | 24 | // Displays results 25 | System.out.printf("%s%8s%n", "Sum", "Count"); 26 | for (int i = 2; i < sumCount.length; i++) 27 | { 28 | System.out.printf("%3d%8d%n", i, sumCount[i]); 29 | } 30 | } // end method main 31 | } // end class DiceSum 32 | -------------------------------------------------------------------------------- /Chapter06/Exercises/6.27/Sieveoferatosthenes.java: -------------------------------------------------------------------------------- 1 | // Show all the prime numbers between 2 and 999 using an array 2 | // @Author: Adam Janecka 3 | package pkg6_27; 4 | 5 | public class SieveofEratosthenes { 6 | 7 | public static void main(String[] args) { 8 | 9 | boolean[] prime = new boolean[1000]; 10 | 11 | // Set all values of array to true 12 | for (int i = 0; i < prime.length; i++) 13 | prime[i] = true; 14 | 15 | for (int i = 2; i < prime.length; i++) 16 | { 17 | // If the element is true 18 | if(prime[i]) 19 | { 20 | //Iterate through the array and set all multiples to false 21 | for (int j = i;j * i < prime.length; j++) 22 | prime[i * j] = false; 23 | } 24 | } 25 | 26 | // Display all prime numbers 27 | for (int i = 2; i < prime.length; i++) 28 | { 29 | if (prime[i]) 30 | System.out.printf("%d%n", i); 31 | 32 | } 33 | } // end method main 34 | } // end class SieveofEratosthenes 35 | -------------------------------------------------------------------------------- /Chapter06/Exercises/6.29/Fibonacci.java: -------------------------------------------------------------------------------- 1 | // Calculates nth Fibonacci number 2 | // @Author: Adam Janecka 3 | package pkg6_29; 4 | import java.util.Scanner; 5 | 6 | public class Fibonacci { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | double num; // Number user enters 12 | double fibnum; // The Fibonacci number at the nth location 13 | 14 | System.out.print("Enter number to find the nth Fibonacci number: "); 15 | num = input.nextInt(); 16 | 17 | fibnum = fibonacci(num); 18 | 19 | // Display nth Fibonacci number 20 | System.out.printf("The Fibonacci number is %.2f%n", fibnum); 21 | System.out.print("The highest Fibonacci number that can be displayed is the 47th number\n"); 22 | } // end method main 23 | 24 | // Calcuates the Nth fibonacci number 25 | public static double fibonacci(double num) 26 | { 27 | double num1 = 0; // First three numbers of Fibonacci sequence as default 28 | double num2 = 1; 29 | double num3 = 1; 30 | 31 | if(num == 1) 32 | return num1; 33 | else if(num == 2) 34 | return num2; 35 | else 36 | { 37 | for(int i = 2; i < num; i++) 38 | { 39 | num3 = num2 + num1; 40 | num1 = num2; 41 | num2 = num3; 42 | } 43 | return num3; 44 | } 45 | } // end method fibonacci 46 | } // end class Fibonacci 47 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.01/Account.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.1: Account.java 2 | // Account class that contians a name instance variable 3 | // and methods to set and get its value 4 | package pkg7_01; 5 | 6 | public class Account { 7 | 8 | private String name; // Instance variable 9 | 10 | // method to set the name in the object 11 | public void setName(String name) 12 | { 13 | this.name = name; // store the name 14 | } 15 | 16 | // method to retrieve the name from the object 17 | public String getName() 18 | { 19 | return name; // return value of name to caller 20 | } 21 | } // end class Account 22 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.02/AccountTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.2: AccountTest.java 2 | // Creating and manipulating an Account object 3 | package pkg7_02; 4 | import java.util.Scanner; 5 | 6 | public class AccountTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | // create a Scanner object to obtain input from the command window 11 | Scanner input = new Scanner(System.in); 12 | 13 | // create an Account object and assign it to MyAccount 14 | Account myAccount = new Account(); 15 | 16 | // display initial value of name (null) 17 | System.out.printf("Initial name is: %s%n%n", myAccount.getName()); 18 | 19 | // prompt for and read name 20 | System.out.println("Please enter the name:"); 21 | String theName = input.nextLine(); // read a line of text 22 | myAccount.setName(theName); // put theName in myAccount 23 | System.out.println(); // outputs a blank line 24 | 25 | // display the name stored in object myAccount 26 | System.out.printf("Name in object myAccount is:%n%s%n", 27 | myAccount.getName()); 28 | } // end method main 29 | } // end class AccountTest 30 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.05/Account.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.5: Account.java 2 | // Account class with a constructor that initializes the name 3 | package pkg7_05; 4 | 5 | public class Account { 6 | 7 | private String name; // instance variable 8 | 9 | // constructor initializes name with parameter name 10 | public Account(String name) // constructor name is class name 11 | { 12 | this.name = name; 13 | } 14 | 15 | // method to set the name 16 | public void setName(String name) 17 | { 18 | this.name = name; 19 | } 20 | 21 | // method to retrieve the name 22 | public String getName() 23 | { 24 | return name; 25 | } 26 | } // end class Account 27 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.06/AccountTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.6: AccountTest.java 2 | // Using the Account constructor to initialize the name instance 3 | // variable at the time each Account object is created. 4 | package pkg7_06; 5 | 6 | public class AccountTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | // create two Account objects 11 | Account account1 = new Account("Jane Green"); 12 | Account account2 = new Account("John Blue"); 13 | 14 | // display initial value of name for each Account 15 | System.out.printf("account1 name is: %s%n", account1.getName()); 16 | System.out.printf("account2 name is: %s%n", account2.getName()); 17 | } // end method main 18 | } // end class AccountTest 19 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.08/Account.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.8: Account.java 2 | // Account class with a double instance variable balance and a constructor 3 | // and depoist method that perform validation 4 | package pkg7_08; 5 | 6 | public class Account { 7 | 8 | private String name; // instance variable 9 | private double balance; // instance variable 10 | 11 | // Account constructor that receives two parameters 12 | public Account(String name, double balance) 13 | { 14 | this.name = name; // assign name to instance variable name 15 | 16 | // validate that the balannce is greater than 0.0; if it's not, 17 | // instance variable balance keeps its default initial value of 0.0 18 | if (balance > 0.0) 19 | this.balance = balance; 20 | } // end constructor 21 | 22 | // method that deposits (adds) only a valid amount to the balance 23 | public void deposit(double depositAmount) 24 | { 25 | if (depositAmount > 0.0) // if the depositAmount is valid 26 | balance += depositAmount; 27 | } // end method deposit 28 | 29 | // method returns the account balance 30 | public double getBalance() 31 | { 32 | return balance; 33 | } // end method getBalance 34 | 35 | // method that sets the name 36 | public void setName(String name) 37 | { 38 | this.name = name; 39 | } // end method setName 40 | 41 | // method that returns the name 42 | public String getName() 43 | { 44 | return name; // give value of name back to caller 45 | } // end method getName 46 | } // end class Account 47 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.11/Card.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.11: Card.java 2 | // Card class represents a playing card 3 | package pkg7_11; 4 | 5 | public class Card { 6 | 7 | private final String face; // face of card ("Ace", "Deuce", ...) 8 | private final String suit; // suite of card ("Hearts", "Diamonds", ...) 9 | 10 | // two-argument constructor initializes card's face and suit 11 | public Card(String cardFace, String cardSuit) 12 | { 13 | this.face = cardFace; // initialize face of card 14 | this.suit = cardSuit; // initialize suit of card 15 | } // end constructor 16 | 17 | // return String representation of Card 18 | public String toString() 19 | { 20 | return face + " of " + suit; 21 | } // end method toString 22 | } // end class Card 23 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.13/DeckOfCardsTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.13: DeckOfCardsTest.java 2 | // Card shuffling and dealing 3 | package pkg7_13; 4 | 5 | public class DeckOfCardsTest { 6 | 7 | // execute application 8 | public static void main(String[] args) { 9 | 10 | DeckOfCards myDeckOfCards = new DeckOfCards(); 11 | myDeckOfCards.shuffle(); // place Cards in random order 12 | 13 | // print all 52 Cards in the order in which they are dealt 14 | for (int i = 1; i <= 52; i++) 15 | { 16 | // deal and display a Card 17 | System.out.printf("%-19s", myDeckOfCards.dealCard()); 18 | 19 | if (i % 4 == 0) // output a newline after every fourth card 20 | System.out.println(); 21 | } 22 | } // end method main 23 | } // end class DeckOfCardsTest 24 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.15/GradeBookTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.15: GradeBookTest.java 2 | // GradeBookTest creates a GradeBook object using an array of grades, 3 | // then invokes method processGrades to analyze them. 4 | package pkg7_15; 5 | 6 | public class GradeBookTest { 7 | 8 | // main method begins program execution 9 | public static void main(String[] args) 10 | { 11 | // array of student grades 12 | int[] gradesArray = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87}; 13 | 14 | GradeBook myGradeBook = new GradeBook( 15 | "CS01 Introduction to Java Programming", gradesArray); 16 | System.out.printf("Welcome to the grade book for%n%s%n%n", 17 | myGradeBook.getCourseName()); 18 | myGradeBook.processGrades(); 19 | } // end method main 20 | } // end class GradeBookTest 21 | -------------------------------------------------------------------------------- /Chapter07/Examples/7.17/GradeBookTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.17: GradeBookTest.java 2 | // GradeBookTest creates a GradeBook object using a two-dimensional array 3 | // of grades, then invokes method processGrades to analyze them 4 | package pkg7_17; 5 | 6 | public class GradeBookTest { 7 | 8 | // main method begins program execution 9 | public static void main(String[] args) { 10 | 11 | // two-dimensional array of student grades 12 | int[][] gradesArray = {{87, 96, 70}, 13 | {68, 87, 90}, 14 | {94, 100, 90}, 15 | {100, 81, 82}, 16 | {83, 65, 85}, 17 | {78, 87, 65}, 18 | {85, 75, 83}, 19 | {91, 94, 100}, 20 | {76, 72, 84}, 21 | {87, 93, 73}}; 22 | 23 | GradeBook myGradeBook = new GradeBook( 24 | "CS101 Introduction to Java Programming", gradesArray); 25 | System.out.printf("Welcome to the grade book for%n%s%n%n", 26 | myGradeBook.getCourseName()); 27 | myGradeBook.processGrades(); 28 | } // end method main 29 | } // end class GradeBookTest 30 | -------------------------------------------------------------------------------- /Chapter07/Exercises/7.11/InvoiceTest.java: -------------------------------------------------------------------------------- 1 | // Test application for Invoice class 2 | // @Author: Adam Janecka 3 | package pkg7_11; 4 | 5 | public class InvoiceTest { 6 | 7 | public static void main(String[] args) 8 | { 9 | 10 | Invoice product = new Invoice("12005", "Battery Powered Drill", 3, 5.65); 11 | System.out.printf("Product number: %s", product.getNumber()); 12 | System.out.printf("\nDescription: %s", product.getDescription()); 13 | System.out.printf("\nQuantity: %d", product.getQuantity()); 14 | System.out.printf("\nPrice Per Unit: $%.2f", product.getPrice()); 15 | System.out.printf("\nInvoice Amount: $%.2f%n", product.getInvoiceAmount()); 16 | } 17 | } // end class InvoiceTest 18 | -------------------------------------------------------------------------------- /Chapter07/Exercises/7.12/Employee.java: -------------------------------------------------------------------------------- 1 | // Create employee class to display name and monthly salary 2 | // @Author: Adam Janecka 3 | package pkg7_12; 4 | 5 | public class Employee { 6 | 7 | private String firstName; 8 | private String lastName; 9 | private double salary; 10 | 11 | // Constructor 12 | public Employee(String first, String last, double salary) 13 | { 14 | this.firstName = first; 15 | this.lastName = last; 16 | this.salary = salary; 17 | } // End constructor 18 | 19 | // Set method for first name 20 | public void setFirstName(String first) 21 | { 22 | this.firstName = first; 23 | } // end method setFirstName 24 | 25 | // Get first name 26 | public String getFirstName() 27 | { 28 | return firstName; 29 | } // end method getFirstName 30 | 31 | // Set last name 32 | public void setLastName(String last) 33 | { 34 | this.lastName = last; 35 | } // end method setLastName 36 | 37 | // Get last name 38 | public String getLastName() 39 | { 40 | return lastName; 41 | } // end method getLastName 42 | 43 | // Set monthly salary 44 | public void setSalary(double salary) 45 | { 46 | if (salary > 0) 47 | this.salary = salary; 48 | } // end method setSalary; 49 | 50 | // Get monthly salary 51 | public double getSalary() 52 | { 53 | return salary; 54 | } // end method getSalary 55 | } // end class Employee 56 | -------------------------------------------------------------------------------- /Chapter07/Exercises/7.12/EmployeeTest.java: -------------------------------------------------------------------------------- 1 | // Application to test Employee class 2 | // @Author: Adam Janecka 3 | package pkg7_12; 4 | 5 | public class EmployeeTest { 6 | 7 | public static void main(String[] args) 8 | { 9 | // create employee objects 10 | Employee employee1 = new Employee("John", "Smith", 725); 11 | Employee employee2 = new Employee("Sarah", "Johnson", 1000); 12 | 13 | // Display info 14 | System.out.printf("%s %s%nSalary: $%.2f%n", employee1.getFirstName(), 15 | employee1.getLastName(),employee1.getSalary() * 12); 16 | System.out.printf("%s %s%nSalary: $%.2f%n%n", employee2.getFirstName(), 17 | employee2.getLastName(),employee2.getSalary() * 12); 18 | 19 | // Display salary with 10% raise 20 | System.out.printf("%s %s%nSalary after raise: $%.2f%n", employee1.getFirstName(), 21 | employee1.getLastName(),(employee1.getSalary() * 12) * 1.10); 22 | System.out.printf("%s %s%nSalary after raise: $%.2f%n", employee2.getFirstName(), 23 | employee2.getLastName(),(employee2.getSalary() * 12) * 1.10); 24 | } // end method main 25 | } // end class EmployeeTest 26 | -------------------------------------------------------------------------------- /Chapter07/Exercises/7.13/Date.java: -------------------------------------------------------------------------------- 1 | // Create a class to display the date 2 | // @Author: Adam Janecka 3 | package pkg7_13; 4 | 5 | public class Date { 6 | 7 | private int month; 8 | private int day; 9 | private int year; 10 | 11 | // Constructor 12 | public Date(int month, int day, int year) 13 | { 14 | setMonth(month); 15 | setDay(day); 16 | setYear(year); 17 | } // end constructor 18 | 19 | // Displays date in month/day/year format 20 | public void displayDate() 21 | { 22 | System.out.printf("%d/%d/%d", month, day, year); 23 | } // end method displayDate 24 | 25 | // set month value 26 | public void setMonth(int month) 27 | { 28 | this.month = month; 29 | } // end method setMonth 30 | 31 | // Return the month value 32 | public int getMonth() 33 | { 34 | return month; 35 | } // end method getMonth 36 | 37 | // set day value 38 | public void setDay(int day) 39 | { 40 | this.day = day; 41 | } // end method setDay 42 | 43 | // Returns day value 44 | public int getDay() 45 | { 46 | return day; 47 | } // end method getDay 48 | 49 | // set year value 50 | public void setYear(int year) 51 | { 52 | this.year = year; 53 | } // end method setYear 54 | 55 | // get year value 56 | public int getYear() 57 | { 58 | return year; 59 | } // end method getYear 60 | } // end class Date 61 | -------------------------------------------------------------------------------- /Chapter07/Exercises/7.13/DateTest.java: -------------------------------------------------------------------------------- 1 | // Application to test Date class 2 | // @Author: Adam Janecka 3 | package pkg7_13; 4 | 5 | public class DateTest { 6 | 7 | public static void main(String[] args) 8 | { 9 | // Displays the date given to constructor 10 | Date today = new Date(7, 21, 2017); 11 | today.displayDate(); 12 | System.out.println(); 13 | } // end method main 14 | } // end class DateTest 15 | -------------------------------------------------------------------------------- /Chapter07/Exercises/7.14/Account.java: -------------------------------------------------------------------------------- 1 | // Fig. 7.8: Account.java 2 | // Account class with a double instance variable balance and a constructor 3 | // and depoist method that perform validation 4 | package pkg7_14; 5 | 6 | public class Account { 7 | 8 | private String name; // instance variable 9 | private double balance; // instance variable 10 | 11 | // Account constructor that receives two parameters 12 | public Account(String name, double balance) 13 | { 14 | this.name = name; // assign name to instance variable name 15 | 16 | // validate that the balannce is greater than 0.0; if it's not, 17 | // instance variable balance keeps its default initial value of 0.0 18 | if (balance > 0.0) 19 | this.balance = balance; 20 | } // end constructor 21 | 22 | // method that deposits (adds) only a valid amount to the balance 23 | public void deposit(double depositAmount) 24 | { 25 | if (depositAmount > 0.0) // if the depositAmount is valid 26 | balance += depositAmount; 27 | } // end method deposit 28 | 29 | // method returns the account balance 30 | public double getBalance() 31 | { 32 | return balance; 33 | } // end method getBalance 34 | 35 | // method that sets the name 36 | public void setName(String name) 37 | { 38 | this.name = name; 39 | } // end method setName 40 | 41 | // method that returns the name 42 | public String getName() 43 | { 44 | return name; // give value of name back to caller 45 | } // end method getName 46 | } // end class Account 47 | -------------------------------------------------------------------------------- /Chapter07/Exercises/7.15/GradeBookTest.java: -------------------------------------------------------------------------------- 1 | // Application to test GradeBook class 2 | // @Author: Adam Janecka 3 | package pkg7_15; 4 | 5 | public class GradeBookTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | GradeBook book = new GradeBook("Java Programming", 4, 3); 10 | 11 | // Display initial gradebook 12 | book.outputGrades(); 13 | 14 | // Enter grades for all exams 15 | for (int i = 1; i <= 4; i++) 16 | { 17 | for (int j = 1; j <= 3; j++) 18 | book.setGrade(i, j); 19 | } 20 | 21 | // Display new gradebook 22 | book.outputGrades(); 23 | } // end method main 24 | } // end class GradeBookTest 25 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.01/Time1.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.1: Time1.java 2 | // Time1 class declaration maintains the time in 24-hour format. 3 | package pkg8_02; 4 | 5 | public class Time1 { 6 | 7 | private int hour; // 0 - 23 8 | private int minute; // 0 - 59 9 | private int second; // 0 - 59 10 | 11 | // set a new time value using universal time; throw an 12 | // exception if the hour, minute or second is invalid 13 | public void setTime(int hour, int minute, int second) 14 | { 15 | // validate hour, minute and second 16 | if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || 17 | second < 0 || second >= 60) 18 | { 19 | throw new IllegalArgumentException( 20 | "hour, minute and/or second was out of range"); 21 | } 22 | 23 | this.hour = hour; 24 | this.minute = minute; 25 | this.second = second; 26 | } // end method setTime 27 | 28 | // convert to String in universal-time format (HH:MM:SS) 29 | public String toUniversalString() 30 | { 31 | return String.format("%02d:%02d:%02d", hour, minute, second); 32 | } // end method toUniversalString 33 | 34 | // convert to String in standard-time format (H:MM:SS AM or PM) 35 | public String toString() 36 | { 37 | return String.format("%d:%02d:%02d %s", 38 | ((hour == 0 || hour == 12) ? 12: hour % 12), 39 | minute, second, (hour < 12 ? "AM" : "PM")); 40 | } // end method toString 41 | } // end class Time1 42 | 43 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.02/Time1Test.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.2: Time1Test.java 2 | // Time1 object used in an app 3 | package pkg8_02; 4 | 5 | public class Time1Test { 6 | 7 | public static void main(String[] args) { 8 | 9 | // create and initialize a Time1 object 10 | Time1 time = new Time1(); // invokes Time1 constructor 11 | 12 | // output string representation of the time 13 | displayTime("After time object is created", time); 14 | System.out.println(); 15 | 16 | // change time and output updated time 17 | time.setTime(13, 27, 6); 18 | displayTime("After calling setTime", time); 19 | System.out.println(); 20 | 21 | // attempt to set time with invalid values 22 | try 23 | { 24 | time.setTime(99,99,99); // all values out of range 25 | } 26 | catch(IllegalArgumentException e) 27 | { 28 | System.out.printf("Exception: %s%n%n", e.getMessage()); 29 | } 30 | 31 | // display time after attempt to set invalid values 32 | displayTime("After calling setTime with invalid values", time); 33 | } // end method main 34 | 35 | // displays a Time1 object in 24-hour and 12-hour formats 36 | private static void displayTime(String header, Time1 t) 37 | { 38 | System.out.printf("%s%nUniversal Time: %s%nStandard time: %s%n", 39 | header, t.toUniversalString(), t.toString()); 40 | } // end method displayTime 41 | } // end class Time1Test 42 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.03/MemberAccessTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.3: MemberAccessTest.java 2 | // Private members of class Time1 are not accessible 3 | package pkg8_03; 4 | 5 | public class MemberAccessTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | Time1 time = new Time1(); // create and initialize Time1 object 10 | 11 | time.hour = 7; // error: hour has private acces in Time1 12 | time.minute = 15; // error: minute has private access in Time1 13 | time.second = 30; // error: second has private acces in Time1 14 | } // end method main 15 | } // end class MemberAccessTest 16 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.06/Time2Test.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.6: Time2Test.java 2 | // Overloaded constructors used to initialize Time2 objects. 3 | package pkg8_06; 4 | 5 | public class Time2Test { 6 | 7 | public static void main(String[] args) { 8 | 9 | Time2 t1 = new Time2(); // 00:00:00 10 | Time2 t2 = new Time2(2); // 02:00:00 11 | Time2 t3 = new Time2(21, 34); // 21:34:00 12 | Time2 t4 = new Time2(12, 25, 42); // 12:25:42 13 | Time2 t5 = new Time2(t4); // 12:25:42 14 | 15 | System.out.println("Constructed with:"); 16 | displayTime("t1: all default arguments", t1); 17 | displayTime("t2: hour specified; default minute and second", t2); 18 | displayTime("t3: hour and minute specified; default second", t3); 19 | displayTime("t4: hour, minute and second specified", t4); 20 | displayTime("t5: Time2 object t4 specified", t5); 21 | 22 | // attempt to initialize t6 with invalid values 23 | try 24 | { 25 | Time2 t6 = new Time2(27, 74, 99); // invalid values 26 | } 27 | catch (IllegalArgumentException e) 28 | { 29 | System.out.printf("%nException while initializing t6: %s%n", 30 | e.getMessage()); 31 | } 32 | } // end method main 33 | 34 | // displays a Time2 object in 24-hour and 12-hour formats 35 | private static void displayTime(String header, Time2 t) 36 | { 37 | System.out.printf("%s%n %s%n %s%n", 38 | header, t.toUniversalString(), t.toString()); 39 | } // end method displayTime 40 | } // end class Time2Test 41 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.08/Employee.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.8: Employee.java 2 | // Employee class with references to other objects. 3 | package pkg8_08; 4 | 5 | public class Employee { 6 | 7 | private String firstName; 8 | private String lastName; 9 | private Date birthDate; 10 | private Date hireDate; 11 | 12 | // constructor to initialize name, birth date and hire date 13 | public Employee(String firstName, String lastName, Date birthDate, 14 | Date hireDate) 15 | { 16 | this.firstName = firstName; 17 | this.lastName = lastName; 18 | this.birthDate = birthDate; 19 | this.hireDate = hireDate; 20 | } // end constructor 21 | 22 | // convert Employoee to String format 23 | public String toString() 24 | { 25 | return String.format("%s, %s Hired: %s Birthday: %s", 26 | lastName, firstName, hireDate, birthDate); 27 | } // end method toString 28 | } // end method Employee 29 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.09/EmployeeTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.9: EmployeeTest.java 2 | // Composition demonstration 3 | package pkg8_09; 4 | 5 | public class EmployeeTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | Date birth = new Date(7, 24, 1949); 10 | Date hire = new Date(3, 12, 1988); 11 | Employee employee = new Employee("Bob", "Blue", birth, hire); 12 | 13 | System.out.println(employee); 14 | } // end method main 15 | } // end class EmployeeTest 16 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.10/Book.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.10: Book.java 2 | // Declaring an enum type with a constructor and explicit instance fields 3 | // and accessors for these fields 4 | 5 | public enum Book { 6 | 7 | // declare constants of enum type 8 | JHTP("Java How to Program", "2015"), 9 | CHTP("C How to Program", "2013"), 10 | IW3HTP("Internet & World Wide Web How to Program", "2012"), 11 | CPPHTP("C++ How to Program", "2014"), 12 | VBHTP("Visual Basic How to Program", "2014"), 13 | CSHARPHTP("Visual C# How to Program", "2014"); 14 | 15 | // instance fields 16 | private final String title; // book title 17 | private final String copyrightYear; // copyright year 18 | 19 | // enum constructor 20 | Book(String title, String copyrightYear) 21 | { 22 | this.title = title; 23 | this.copyrightYear = copyrightYear; 24 | } // end constructor 25 | 26 | // accessor for field title 27 | public String getTitle() 28 | { 29 | return title; 30 | } // end method getTitle 31 | 32 | // accessor for field copyrightYear 33 | public String getCopyrightYear() 34 | { 35 | return copyrightYear; 36 | } // end method getCopyrightYear 37 | } // end enum Book 38 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.11/EnumTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.11: EnumTest.java 2 | // Testing enum type Book 3 | package pkg8_11; 4 | import java.util.EnumSet; 5 | 6 | public class EnumTest { 7 | 8 | public static void main(String[] args) { 9 | System.out.println("All books:"); 10 | 11 | // print all books in enum Book 12 | for (Book book : Book.values()) 13 | System.out.printf("%-10s%-45s%s%n", book, 14 | book.getTitle(), book.getCopyrightYear()); 15 | 16 | System.out.printf("%nDisplay a range of enum constants:%n"); 17 | 18 | // print first four books 19 | for (Book book : EnumSet.range(Book.JHTP, Book.CPPHTP)) 20 | System.out.printf("%-10s%-45s%s%n", book, 21 | book.getTitle(), book.getCopyrightYear()); 22 | } // end method main 23 | } // end class EnumTest 24 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.12/Employee.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.12: Employee.java 2 | // static variable used to maintain a count of the number of 3 | // Employee objects in memory 4 | package pkg8_12; 5 | 6 | public class Employee { 7 | 8 | private static int count = 0; // number of Employees created 9 | private String firstName; 10 | private String lastName; 11 | 12 | // initialize Employee, add 1 to static count and 13 | // output String indicating that constructor was called 14 | public Employee(String firstName, String lastName) 15 | { 16 | this.firstName = firstName; 17 | this.lastName = lastName; 18 | 19 | ++count; // increment static count of employees 20 | System.out.printf("Employee constructor: %s %s; count = %d%n", 21 | firstName, lastName, count); 22 | } // end constructor 23 | 24 | // get first name 25 | public String getFirstName() 26 | { 27 | return firstName; 28 | } // end method getFirstName 29 | 30 | // get last name 31 | public String getLastName() 32 | { 33 | return lastName; 34 | } // end method getLastName 35 | 36 | // static method to get static count value 37 | public static int getCount() 38 | { 39 | return count; 40 | } // end method getCount 41 | } // end class Employee 42 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.13/EmployeeTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.13: EmployeeTest.java 2 | // static member demonstration 3 | package pkg8_13; 4 | 5 | public class EmployeeTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | // show that count is 0 before creating Employees 10 | System.out.printf("Employees before instantiation: %d%n", 11 | Employee.getCount()); 12 | 13 | // create two Employees; count should be 2 14 | Employee e1 = new Employee("Susan", "Baker"); 15 | Employee e2 = new Employee("Bob", "Blue"); 16 | 17 | // show that count is 2 after creating two Employees 18 | System.out.printf("%nEmployees after instantiation:%n"); 19 | System.out.printf("via e1.getCount(): %d%n", e1.getCount()); 20 | System.out.printf("via e2.getCount(): %d%n", e2.getCount()); 21 | System.out.printf("via Employee.getCount(): %d%n", 22 | Employee.getCount()); 23 | 24 | // get names of Employees 25 | System.out.printf("%nEmployee 1: %s %s%nEmployee 2: %s %s%n", 26 | e1.getFirstName(), e1.getLastName(), 27 | e2.getFirstName(), e2.getLastName()); 28 | } // end method main 29 | } // end class EmployeeTest 30 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.14/StaticImportTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.14: StaticImportTest.java 2 | // Static import of Math class methods 3 | package pkg8_14; 4 | import static java.lang.Math.*; 5 | 6 | public class StaticImportTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | System.out.printf("sqrt(900.0) = %.1f%n", sqrt(900.0)); 11 | System.out.printf("ceil(-9.8) = %.1f%n", ceil(-9.8)); 12 | System.out.printf("E = %f%n", E); 13 | System.out.printf("PI = %f%n", PI); 14 | } // end method main 15 | } // end class StaticImportTest 16 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.15/PackageDataTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 8.15: PackageDataTest.java 2 | // Package-access members of a class are accessible by other classes 3 | // in the same package. 4 | package pkg8_15; 5 | 6 | public class PackageDataTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | PackageData packageData = new PackageData(); 11 | 12 | // output String representation of packageData 13 | System.out.printf("After instantiation:%n%s%n", packageData); 14 | 15 | // change package access data in packageData object 16 | packageData.number = 77; 17 | packageData.string = "Goodbye"; 18 | 19 | // output String representation of packageData 20 | System.out.printf("%nAfter changing values:%n%s%n", packageData); 21 | } // end method main 22 | } // end class PackageDataTest 23 | 24 | // class with package access instance variables 25 | class PackageData 26 | { 27 | int number; // package-access instance variable 28 | String string; // package-access instance variable 29 | 30 | // constructor 31 | public PackageData() 32 | { 33 | number = 0; 34 | string = "Hello"; 35 | } // end constructor 36 | 37 | // return PackageData to object String representation 38 | public String toString() 39 | { 40 | return String.format("number: %d; string: %s", number, string); 41 | } // end method toString 42 | } // end class PackageData 43 | -------------------------------------------------------------------------------- /Chapter08/Examples/8.16/Interest.java: -------------------------------------------------------------------------------- 1 | // Interest.java 2 | // Compound-interest calculations with BigDecimal. 3 | package pkg8_16; 4 | import java.math.BigDecimal; 5 | import java.text.NumberFormat; 6 | 7 | public class Interest { 8 | 9 | public static void main(String[] args) { 10 | 11 | // initial principal amount before interest 12 | BigDecimal principal = BigDecimal.valueOf(1000.0); 13 | BigDecimal rate = BigDecimal.valueOf(0.05); // interest rate 14 | 15 | // display headers 16 | System.out.printf("%s%20s%n", "Year", "Amount on deposit"); 17 | 18 | // calculate amount on deposit for each of ten years 19 | for (int year = 1; year <= 10; year++) 20 | { 21 | // calculate new amount for specified year 22 | BigDecimal amount = 23 | principal.multiply(rate.add(BigDecimal.ONE).pow(year)); 24 | 25 | // display the year and the amount 26 | System.out.printf("%4d%20s%n", year, 27 | NumberFormat.getCurrencyInstance().format(amount)); 28 | } 29 | } // end method main 30 | } // end class Interest 31 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.04/Rectangle.java: -------------------------------------------------------------------------------- 1 | // Rectangle class to calculate the area and perimeter of a Rectangle 2 | // @Author: Adam Janecka 3 | package pkg8_04; 4 | 5 | public class Rectangle { 6 | 7 | private double length = 1; 8 | private double width = 1; 9 | 10 | public Rectangle(double length, double width) 11 | { 12 | setLength(length); 13 | setWidth(width); 14 | } // end constructor 15 | 16 | public Rectangle() 17 | { 18 | length = 1; 19 | width = 1; 20 | } // end no paramter constructor 21 | 22 | public double Perimeter() 23 | { 24 | return 2 * length + 2 * width; 25 | } // end method Perimeter 26 | 27 | public double Area() 28 | { 29 | return length * width; 30 | } // end method Area 31 | 32 | public void setLength(double length) 33 | { 34 | if (length > 0 && length <= 20) 35 | this.length = length; 36 | else 37 | throw new IllegalArgumentException("length must be bewteen 1 and 20."); 38 | } // end method setLength 39 | 40 | public void setWidth(double width) 41 | { 42 | if (width > 0 && width <= 20) 43 | this.width = width; 44 | else 45 | throw new IllegalArgumentException("width must be bewteen 1 and 20."); 46 | } // end method setWidth 47 | 48 | public double getLength() 49 | { 50 | return length; 51 | } // end method getLength 52 | 53 | public double getWidth() 54 | { 55 | return width; 56 | } // end method getWidth 57 | } // end class Rectangle 58 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.04/RectangleTest.java: -------------------------------------------------------------------------------- 1 | // Test application for class Rectangle 2 | package pkg8_04; 3 | 4 | public class RectangleTest { 5 | 6 | public static void main(String[] args) 7 | { 8 | Rectangle rectangle = new Rectangle(4.25, 5); 9 | 10 | System.out.printf("Length: %.2f%nWidth: %.2f", rectangle.getLength(), 11 | rectangle.getWidth()); 12 | System.out.printf("%nPerimeter: %.2f%nArea: %.2f%n", rectangle.Perimeter(), 13 | rectangle.Area()); 14 | } // end method main 15 | } // end class RectangleTest 16 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.06/SavingsAccount.java: -------------------------------------------------------------------------------- 1 | // Class to find the amount in account while applying interest 2 | // @Author: Adam Janecka 3 | package pkg8_06; 4 | 5 | public class SavingsAccount { 6 | 7 | private static double annualInterestRate; 8 | private double savingsBalance; 9 | 10 | public SavingsAccount(double savingsBalance) 11 | { 12 | this.savingsBalance = savingsBalance; 13 | } 14 | // Calculates the monthly interest rate 15 | public double calculateMonthlyInterest() 16 | { 17 | double monthlyInterest = savingsBalance * (annualInterestRate / 12); 18 | double total = savingsBalance + monthlyInterest; 19 | savingsBalance = total; 20 | 21 | return total; 22 | } // end method calculateMonthlyInterest 23 | 24 | // Modifys the annual interest rate 25 | public static void modifyInterestRate(double rate) 26 | { 27 | annualInterestRate = rate; 28 | } // end method modifyInterestRate 29 | } // end class SavingsAccount 30 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.06/SavingsAccountTest.java: -------------------------------------------------------------------------------- 1 | // Test class for SavingsAccount 2 | // @Author: Adam Janecka 3 | package pkg8_06; 4 | 5 | public class SavingsAccountTest { 6 | 7 | public static void main(String args[]) 8 | { 9 | SavingsAccount account1 = new SavingsAccount(2000); 10 | SavingsAccount account2 = new SavingsAccount(3000); 11 | 12 | // Make annual interest rate 4% 13 | account1.modifyInterestRate(.04); 14 | 15 | // Prints out balance for next 12 months 16 | System.out.println("Account with 4% annual interest"); 17 | System.out.println("Month Account1 Account2"); 18 | for (int i = 0; i < 12; i++) 19 | { 20 | System.out.printf("%5d%11.2f%11.2f%n", i + 1, account1.calculateMonthlyInterest(), 21 | account2.calculateMonthlyInterest()); 22 | } 23 | 24 | account1.modifyInterestRate(.05); 25 | 26 | // Prints out next month with 5% interest 27 | System.out.println("Account with 5% annual interest"); 28 | System.out.printf("%5d%11.2f%11.2f%n", 13, account1.calculateMonthlyInterest(), 29 | account2.calculateMonthlyInterest()); 30 | } // end method main 31 | } // end class SavingsAccountTest 32 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.08/DateTest.java: -------------------------------------------------------------------------------- 1 | // Test application for Date class 2 | // @Author: Adam Janecka 3 | package pkg8_08; 4 | 5 | public class DateTest { 6 | 7 | public static void main(String args[]) 8 | { 9 | Date day1 = new Date(4, 30, 1999); // Test going into a new month 10 | Date day2 = new Date(12, 31, 1999); // Test going into a new year 11 | Date day3 = new Date(2, 28, 2004); // Test for leap year 12 | 13 | // Increment days by one 14 | day1.nextDay(); 15 | day2.nextDay(); 16 | day3.nextDay(); 17 | 18 | // Shows new values for date objects 19 | System.out.printf("%nDates incremented by 1: %n"); 20 | System.out.printf("Date 1: %s%nDate 2: %s%nDate 3: %s%n", day1, day2, day3); 21 | } // end method main 22 | 23 | } // end class DateTest 24 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.09/StaticImportTest.java: -------------------------------------------------------------------------------- 1 | // Modify Fig 8.14 to import each item individually 2 | // @Author: Adam Janecka 3 | package pkg8_09; 4 | import static java.lang.Math.E; 5 | import static java.lang.Math.PI; 6 | import static java.lang.Math.sqrt; 7 | import static java.lang.Math.ceil; 8 | 9 | public class StaticImportTest { 10 | 11 | public static void main(String[] args) { 12 | 13 | System.out.printf("sqrt(900.0) = %.1f%n", sqrt(900.0)); 14 | System.out.printf("ceil(-9.8) = %.1f%n", ceil(-9.8)); 15 | System.out.printf("E = %f%n", E); 16 | System.out.printf("PI = %f%n", PI); 17 | } // end method main 18 | } // end class StaticImportTest 19 | 20 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.10/EnumTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package pkg8_10; 7 | 8 | /** 9 | * 10 | * @author Adam Janecka 11 | */ 12 | public class EnumTest { 13 | 14 | /** 15 | * @param args the command line arguments 16 | */ 17 | public static void main(String[] args) { 18 | 19 | System.out.println("Light\tDuration"); 20 | 21 | for (TrafficLight light : TrafficLight.values()) 22 | { 23 | System.out.printf("%s\t%d%n", light, light.getDuration()); 24 | } 25 | } // end method main 26 | 27 | } // end class EnumTest 28 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.10/TrafficLight.java: -------------------------------------------------------------------------------- 1 | // Create an enum class for a traffic light 2 | // @Author: Adam Janecka 3 | package pkg8_10; 4 | 5 | public enum TrafficLight { 6 | 7 | RED(80), 8 | YELLOW(10), 9 | GREEN(65); 10 | 11 | 12 | private final int duration; 13 | 14 | TrafficLight(int duration) 15 | { 16 | this.duration = duration; 17 | } // end constructor 18 | 19 | public int getDuration() 20 | { 21 | return duration; 22 | } // end method getDuration 23 | 24 | } // end class TrafficLight 25 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.11/Complex.java: -------------------------------------------------------------------------------- 1 | // Shows complex numbers as a + bi 2 | // @Author: Adam Janecka 3 | package pkg8_11; 4 | 5 | public class Complex { 6 | 7 | private double real; // Real number portion 8 | private double imaginary; // Imaginary portion 9 | 10 | public Complex() 11 | { 12 | real = 0.0; 13 | imaginary = 0.0; 14 | } // end default constructor 15 | 16 | public Complex(double real, double imaginary) 17 | { 18 | this.real = real; 19 | this.imaginary = imaginary; 20 | } // end constructor 21 | 22 | // Adds complex numbers 23 | public Complex add(Complex add) 24 | { 25 | return new Complex(real + add.real, imaginary + add.imaginary); 26 | } // end method add 27 | 28 | // Subtract two numbers 29 | public Complex subtract(Complex subtract) 30 | { 31 | return new Complex(real - subtract.real, imaginary - subtract.imaginary); 32 | } // end method subtract 33 | 34 | public String toString() 35 | { 36 | return String.format("(%.1f,%.1f)", real,imaginary); 37 | } // end method toString 38 | } // end class Complex 39 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.11/ComplexTest.java: -------------------------------------------------------------------------------- 1 | // Test for Complex class 2 | // @Author: Adam Janecka 3 | package pkg8_11; 4 | 5 | public class ComplexTest { 6 | 7 | 8 | public static void main(String args[]) 9 | { 10 | Complex num1 = new Complex(5, 3); 11 | Complex num2 = new Complex(2, 4); 12 | 13 | // Display initial amounts 14 | System.out.printf("num1 = %s%n", num1); 15 | System.out.printf("num2 = %s%n", num2); 16 | 17 | // Add and subtract operations 18 | System.out.printf("num1 + num2 = %s%n", num1.add(num2)); 19 | System.out.printf("num1 - num2 = %s%n", num1.subtract(num2)); 20 | } // end method main 21 | } // end class ComplexTest 22 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.12/DateAndTimeTest.java: -------------------------------------------------------------------------------- 1 | // Test application for class DateAndTime 2 | // @Author: Adam Janecka 3 | package pkg8_12; 4 | 5 | public class DateAndTimeTest { 6 | 7 | public static void main(String args[]) 8 | { 9 | DateAndTime day1 = new DateAndTime(1, 1, 1, 1, 1, 2000); 10 | DateAndTime day2 = new DateAndTime(23,59,59,12,31,2001); 11 | 12 | System.out.printf("Initial time and date:%n%s%n%s", day1, day2); 13 | 14 | day1.tick(); 15 | day2.tick(); 16 | 17 | System.out.printf("Time and date after increment of one second:%n%s%n%s", day1, day2); 18 | 19 | } // end method main 20 | } // end class DateAndTimeTest 21 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.13/IntegerSetTest.java: -------------------------------------------------------------------------------- 1 | // Test class for IntegerSet 2 | // @Author: Adam Janecka 3 | package pkg8_13; 4 | 5 | public class IntegerSetTest { 6 | 7 | public static void main(String args[]) 8 | { 9 | IntegerSet set1 = new IntegerSet(); 10 | IntegerSet set2 = new IntegerSet(); 11 | 12 | // Displays initial set; values empty 13 | System.out.printf("Set1: %s%nSet2: %s%n", set1, set2); 14 | 15 | // Add elements to both sets 16 | set1.insertElement(5); 17 | set1.insertElement(8); 18 | set1.insertElement(11); 19 | set2.insertElement(11); 20 | set2.insertElement(17); 21 | set2.insertElement(23); 22 | 23 | // Displays new outcome 24 | System.out.printf("%nNew sets%nSet1: %s%nSet2: %s%n", set1, set2); 25 | System.out.printf("Union: %s%n", set1.union(set2).toString()); 26 | System.out.printf("Intersection: %s%n", set1.intersect(set2).toString()); 27 | 28 | // Delete some elements 29 | set1.deleteElement(5); 30 | set2.deleteElement(23); 31 | 32 | // Display new outcome 33 | System.out.printf("%nNew sets%nSet1: %s%nSet2: %s%n", set1, set2); 34 | } // end method main 35 | } // end class IntegerSetTest 36 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.14/DateTest.java: -------------------------------------------------------------------------------- 1 | // Test application for Date class 2 | // @Author: Adam Janecka 3 | package pkg8_14; 4 | 5 | public class DateTest { 6 | 7 | public static void main(String args[]) 8 | { 9 | Date day1 = new Date(4, 30, 1999); // Test default constructor 10 | Date day2 = new Date("February", 28, 2004); // Test with String 11 | Date day3 = new Date(334, 2000); // Test with longDay 12 | 13 | // Increment days by one 14 | day1.nextDay(); 15 | day2.nextDay(); 16 | day3.nextDay(); 17 | 18 | // Shows new values for date objects 19 | System.out.printf("%nDates incremented by 1: %n"); 20 | System.out.printf("Date 1: %s%nDate 2: %s%nDate 3: %s%n", day1, day2, day3); 21 | } // end method main 22 | 23 | } // end class DateTest 24 | -------------------------------------------------------------------------------- /Chapter08/Exercises/8.15/RationalTest.java: -------------------------------------------------------------------------------- 1 | // Test class for Rational application 2 | // @Author: Adam Janecka 3 | package pkg8_15; 4 | 5 | 6 | public class RationalTest { 7 | 8 | public static void main(String[] args) 9 | { 10 | Rational num1 = new Rational(2,4); 11 | Rational num2 = new Rational(3,4); 12 | Rational num3 = new Rational(); 13 | 14 | System.out.printf("num1: %s%n", num1); 15 | System.out.printf("num2: %s%n", num2); 16 | System.out.printf("Sum of numbers is %s%n", Rational.add(num1,num2)); 17 | System.out.printf("Num2 - Num1 equals %s%n", Rational.subtract(num2, num1)); 18 | System.out.printf("Product of numbers is %s%n", Rational.multiply(num1, num2)); 19 | System.out.printf("Quotient of numbers is %s%n", Rational.divide(num1, num2)); 20 | System.out.printf("Num1 as decimal: %.2f%n", Rational.toDecimal(num1)); 21 | } // end method main 22 | 23 | } // end class RationalTest 24 | -------------------------------------------------------------------------------- /Chapter09/Examples/9.05/CommissionEmployeeTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 9.5: CommissionEmployeeTest.java 2 | // CommissionEmployee class test program 3 | package pkg9_05; 4 | 5 | public class CommissionEmployeeTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | // instantiate CommissionEmployee object 10 | CommissionEmployee employee = new CommissionEmployee( 11 | "Sue", "Jones", "222-22-2222", 10000, .06); 12 | 13 | // get commission employee data 14 | System.out.println( 15 | "Employee information obtained by get methods:"); 16 | System.out.printf("%n%s %s%n", "First name is", 17 | employee.getFirstName()); 18 | System.out.printf("%s %s%n", "Last name is", 19 | employee.getLastName()); 20 | System.out.printf("%s %s%n", "Social security number is", 21 | employee.getSocialSecurityNumber()); 22 | System.out.printf("%s %.2f%n", "Gross sales is", 23 | employee.getGrossSales()); 24 | System.out.printf("%s %.2f%n", "Commission rate is", 25 | employee.getCommissionRate()); 26 | 27 | employee.setGrossSales(5000); 28 | employee.setCommissionRate(.1); 29 | 30 | System.out.printf("%n%s:%n%n%s%n", 31 | "Updated employee information obtained by toString", employee); 32 | } // end method main 33 | } // end class CommissionEmployeeTest 34 | 35 | -------------------------------------------------------------------------------- /Chapter09/Examples/9.07/BasePlusCommissionEmployeeTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 9.7: BasePlusCommissionEmployeeTest.java 2 | // BasePlusCommissionEmployee test program 3 | package pkg9_07; 4 | 5 | public class BasePlusCommissionEmployeeTest { 6 | 7 | public static void main(String[] args) { 8 | 9 | // instantiate BasePlusCommissionEmployee object 10 | BasePlusCommissionEmployee employee = 11 | new BasePlusCommissionEmployee( 12 | "Bob", "Lewis", "333-33-3333", 5000, .04, 300); 13 | 14 | // get base-salaried commision employee data 15 | System.out.println( 16 | "Employee information obtained by get methods:%n"); 17 | System.out.printf("%s %s%n", "First name is", 18 | employee.getFirstName()); 19 | System.out.printf("%s %s%n", "Last name is", 20 | employee.getLastName()); 21 | System.out.printf("%s %s%n", "Social security number is", 22 | employee.getSocialSecurityNumber()); 23 | System.out.printf("%s %.2f%n", "Gross sales is", 24 | employee.getGrossSales()); 25 | System.out.printf("%s %.2f%n", "Commission rate is", 26 | employee.getCommissionRate()); 27 | System.out.printf("%s %.2f%n", "Base salary is", 28 | employee.getBaseSalary()); 29 | 30 | employee.setBaseSalary(1000); 31 | 32 | System.out.printf("%n%s:%n%n%s%n", 33 | "Updated employee information obtained by toString", 34 | employee.toString()); 35 | } // end method main 36 | } // end class BasePlusCommissionEmployeeTest 37 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.03/BasePlusCommissionEmployee.java: -------------------------------------------------------------------------------- 1 | // Class BasePlusCommissionEmployee using composition 2 | // @Author: Adam Janecka 3 | 4 | package pkg9_03; 5 | 6 | public class BasePlusCommissionEmployee { 7 | 8 | private CommissionEmployee employee; 9 | private double baseSalary; 10 | 11 | public BasePlusCommissionEmployee(CommissionEmployee employee, double baseSalary) 12 | { 13 | this.employee = employee; 14 | this.baseSalary = baseSalary; 15 | } 16 | 17 | public void setBaseSalary(double baseSalary) 18 | { 19 | this.baseSalary = baseSalary; 20 | } // end method setBaseSalary 21 | 22 | public double getBaseSalary() 23 | { 24 | return baseSalary; 25 | } // end method getBaseSalary 26 | 27 | public String toString() 28 | { 29 | return String.format("%s\n%s %.2f ", employee, 30 | "Base Salary:", getBaseSalary()); 31 | } // end method toString 32 | } // end class BasePlusCommissionEmployee 33 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.03/BasePlusCommissionEmployeeTest.java: -------------------------------------------------------------------------------- 1 | 2 | package pkg9_03; 3 | 4 | public class BasePlusCommissionEmployeeTest { 5 | 6 | public static void main(String[] args) 7 | { 8 | CommissionEmployee commEmployee = new CommissionEmployee 9 | ("Adam", "Janecka", "555-55-5555", 5000, .04); 10 | 11 | double salary = 5000; 12 | 13 | BasePlusCommissionEmployee employee = new 14 | BasePlusCommissionEmployee(commEmployee, salary); 15 | 16 | System.out.println(employee); 17 | } // end method main 18 | } // end class BasePlusCommissionEmployeeTest 19 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.08/Parallelogram.java: -------------------------------------------------------------------------------- 1 | // Parallelogram is a subclass of Quadrilateral 2 | // @Author: Adam Janecka 3 | package pkg9_08; 4 | 5 | public class Parallelogram extends Trapezoid{ 6 | 7 | public Parallelogram(double x1, double y1, double x2, double y2, 8 | double x3, double y3, double x4, double y4) 9 | { 10 | super(x1, y1, x2, y2, x3, y3, x4, y4); 11 | } // end constructor 12 | 13 | // Calculates the width 14 | 15 | public double width() 16 | { 17 | if (getP().getY() == getQ().getY()) 18 | return Math.abs(getP().getX() - getQ().getX()); 19 | else 20 | return Math.abs(getQ().getX() - getR().getX()); 21 | } // end method width 22 | 23 | // Area method for parallelogram 24 | @Override 25 | public double area() 26 | { 27 | return width() * height(); 28 | } // end method area 29 | 30 | @Override 31 | public String toString() 32 | { 33 | return String.format("%s %n%s: %s%n%s: %s%n%s: %s", super.printCoordinates(), 34 | "Height", height(), "Width", width(), "Area", area()); 35 | } // end method toString 36 | } // end class Parallelogram 37 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.08/Point.java: -------------------------------------------------------------------------------- 1 | // Class to show the coordinates of the quadrilateral 2 | // @Author: Adam Janecka 3 | package pkg9_08; 4 | 5 | public class Point { 6 | 7 | private double x, y; 8 | 9 | public Point (double x, double y) 10 | { 11 | this.x = x; 12 | this.y = y; 13 | } // end constructor 14 | 15 | // Return x coordinate 16 | public double getX() 17 | { 18 | return x; 19 | } // end method getX 20 | 21 | // Return y coordinate 22 | public double getY() 23 | { 24 | return y; 25 | } // end method getY 26 | 27 | public String toString() 28 | { 29 | return String.format("(%.2f, %.2f)", getX(), getY()); 30 | } // end method toString 31 | } // end class Point 32 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.08/Quadrilateral.java: -------------------------------------------------------------------------------- 1 | // Create a quadrilateral hierarchy 2 | // @Author: Adam Janecka 3 | package pkg9_08; 4 | 5 | public class Quadrilateral { 6 | 7 | Point p, q, r, s; 8 | 9 | public Quadrilateral(double x1, double y1, double x2, double y2, 10 | double x3, double y3, double x4, double y4) 11 | { 12 | p = new Point(x1, y1); 13 | q = new Point(x2, y2); 14 | r = new Point(x3, y3); 15 | s = new Point(x4, y4); 16 | } // end constructor 17 | 18 | // Get first point 19 | public Point getP() 20 | { 21 | return p; 22 | } // end method getPointW 23 | 24 | // Get second point 25 | public Point getQ() 26 | { 27 | return q; 28 | } // end method getPointX 29 | 30 | // Get third point 31 | public Point getR() 32 | { 33 | return r; 34 | } // end method getPointY 35 | 36 | // Get fourth point 37 | public Point getS() 38 | { 39 | return s; 40 | } // end method getPointZ 41 | 42 | // Prints out the coordinates 43 | public String toString() 44 | { 45 | return String.format("The coordinates in the quadrilateral " 46 | + "are %s, %s, %s, %s", p, q, r, s); 47 | } // end method toString 48 | } // end class Quadrilateral 49 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.08/QuadrilateralTest.java: -------------------------------------------------------------------------------- 1 | // Test class 2 | // @Author: Adam Janecka 3 | package pkg9_08; 4 | 5 | public class QuadrilateralTest { 6 | 7 | public static void main(String[] args) 8 | { 9 | // Create new quadrilaterals 10 | Trapezoid trapezoid = new Trapezoid(0, 0, 0, 3, 5, 0, 3, 3); 11 | Parallelogram parallelogram = new Parallelogram(0, 0, 0, 4, 2, 2, 0,2); 12 | Rectangle rectangle = new Rectangle(0, 0, 0, 4, 6, 4, 6, 0); 13 | Square square = new Square(0, 0, 4, 0, 4, 4, 0, 4); 14 | 15 | System.out.printf("%nTrapezoid: %n%s", trapezoid); 16 | System.out.printf("%n%nParallelogram: %n%s", parallelogram); 17 | System.out.printf("%n%nRectangle: %n%s", rectangle); 18 | System.out.printf("%n%nSquare: %n%s%n", square); 19 | 20 | } // end method main 21 | } // end class QuadrilateralTest 22 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.08/Rectangle.java: -------------------------------------------------------------------------------- 1 | //Rectangle extends class Parallelogram 2 | // @Author: Adam Janecka 3 | package pkg9_08; 4 | 5 | public class Rectangle extends Parallelogram{ 6 | 7 | public Rectangle(double x1, double y1, double x2, double y2, 8 | double x3, double y3, double x4, double y4) 9 | { 10 | super(x1, y1, x2, y2, x3, y3, x4, y4); 11 | } // end constructor 12 | 13 | @Override 14 | public String toString() 15 | { 16 | return String.format("%s", super.toString()); 17 | } // end method toString 18 | } // end class Rectangle 19 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.08/Square.java: -------------------------------------------------------------------------------- 1 | // Square is a subclass of Rectangle 2 | // @Author: Adam Janecka 3 | package pkg9_08; 4 | 5 | public class Square extends Rectangle{ 6 | 7 | public Square(double x1, double y1, double x2, double y2, 8 | double x3, double y3, double x4, double y4) 9 | { 10 | super(x1, y1, x2, y2, x3, y3, x4, y4); 11 | } // end constructor 12 | } // end class Square 13 | -------------------------------------------------------------------------------- /Chapter09/Exercises/9.15/HourlyEmployeeTest.java: -------------------------------------------------------------------------------- 1 | // Test class for HourlyEmployee 2 | package pkg9_15; 3 | 4 | public class HourlyEmployeeTest { 5 | 6 | public static void main(String[] args) 7 | { 8 | HourlyEmployee employee = new HourlyEmployee("Adam", "Janecka", "555-55-5555", 9 | 40.00, 10.00); 10 | 11 | System.out.printf("Output before modfication:%n%s", employee); 12 | 13 | // Change hours for overtime 14 | employee.setHours(45); 15 | 16 | System.out.printf("%nOutput after modification:%n%s", employee); 17 | } // end method main 18 | } // end class HourlyEmployeeTest 19 | -------------------------------------------------------------------------------- /Chapter10/Examples/10.04/Employee.java: -------------------------------------------------------------------------------- 1 | // Fig. 10.4: Employee.java 2 | // Employee abstract superclass 3 | package pkg10_04; 4 | 5 | public abstract class Employee { 6 | 7 | private final String firstName; 8 | private final String lastName; 9 | private final String socialSecurityNumber; 10 | 11 | // constructor 12 | public Employee(String firstName, String lastName, 13 | String socialSecurityNumber) 14 | { 15 | this.firstName = firstName; 16 | this.lastName = lastName; 17 | this.socialSecurityNumber = socialSecurityNumber; 18 | } // end constructor 19 | 20 | // return first name 21 | public String getFirstName() 22 | { 23 | return firstName; 24 | } // end method getFirstName 25 | 26 | public String getLastName() 27 | { 28 | return lastName; 29 | } // end method getLastName 30 | 31 | // return social security number 32 | public String getSocialSecurityNumber() 33 | { 34 | return socialSecurityNumber; 35 | } // end method getSocialSecurityNumber 36 | 37 | // return String representation of Employee object 38 | @Override 39 | public String toString() 40 | { 41 | return String.format("%s %s%nsocial security number: %s", 42 | getFirstName(), getLastName(), getSocialSecurityNumber()); 43 | } // end method toString 44 | 45 | // abstract method must be overridden by concrete subclasses 46 | public abstract double earnings(); // no implementation here 47 | } // end abstract class Employee 48 | -------------------------------------------------------------------------------- /Chapter10/Examples/10.11/Payable.java: -------------------------------------------------------------------------------- 1 | // Fig. 10.11: Payable.java 2 | // Payable interface declaration. 3 | 4 | package pkg10_11; 5 | 6 | public interface Payable { 7 | 8 | double getPaymentAmount(); // calculate payment; no implementation 9 | } // end interface Payable 10 | 11 | -------------------------------------------------------------------------------- /Chapter10/Examples/10.13/Employee.java: -------------------------------------------------------------------------------- 1 | // Fig. 10.13: Employee.java 2 | // Employee abstract superclass that implements Payable 3 | package pkg10_13; 4 | 5 | public abstract class Employee implements Payable{ 6 | 7 | private final String firstName; 8 | private final String lastName; 9 | private final String socialSecurityNumber; 10 | 11 | // constructor 12 | public Employee(String firstName, String lastName, 13 | String socialSecurityNumber) 14 | { 15 | this.firstName = firstName; 16 | this.lastName = lastName; 17 | this.socialSecurityNumber = socialSecurityNumber; 18 | } // end constructor 19 | 20 | // return first name 21 | public String getFirstName() 22 | { 23 | return firstName; 24 | } // end method getFirstName 25 | 26 | public String getLastName() 27 | { 28 | return lastName; 29 | } // end method getLastName 30 | 31 | // return social security number 32 | public String getSocialSecurityNumber() 33 | { 34 | return socialSecurityNumber; 35 | } // end method getSocialSecurityNumber 36 | 37 | // return String representation of Employee object 38 | @Override 39 | public String toString() 40 | { 41 | return String.format("%s %s%nsocial security number: %s", 42 | getFirstName(), getLastName(), getSocialSecurityNumber()); 43 | } // end method toString 44 | 45 | //Note: We do not implement Payable method getPaymentAmount here so 46 | // this class must be declared abstract to avoid a compilation error 47 | } // end abstract class Employee 48 | -------------------------------------------------------------------------------- /Chapter10/Examples/10.15/PayableInterfaceTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 10.15: PayableInterfaceTest.java 2 | // Payable interface test program processing Invoices and 3 | // Employees polymorphically 4 | package pkg10_15; 5 | 6 | public class PayableInterfaceTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | // create four-element Payable array 11 | Payable[] payableObjects = new Payable[4]; 12 | 13 | // populate array with objects that implement Payable 14 | payableObjects[0] = new Invoice("01234", "seat", 2, 375.00); 15 | payableObjects[1] = new Invoice("56789", "tire", 4, 79.95); 16 | payableObjects[2] = 17 | new SalariedEmployee("John", "Smith", "111-11-1111", 800.00); 18 | payableObjects[3] = 19 | new SalariedEmployee("Lisa", "Barnes", "888-88-8888", 1200.00); 20 | 21 | System.out.println( 22 | "Invoices and Employees processed polymorphically: "); 23 | 24 | // generically process each element in array payableObjects 25 | for (Payable currentPayable: payableObjects) 26 | { 27 | // output currentPayable and its appropriate payment amount 28 | System.out.printf("%n%s %n%s: $%,.2f%n", 29 | currentPayable.toString(), // could invoke implicitly 30 | "payment due", currentPayable.getPaymentAmount()); 31 | } 32 | } // end method main 33 | } // end class PayableInterfaceTest 34 | -------------------------------------------------------------------------------- /Chapter10/Exercises/10.13/Circle.java: -------------------------------------------------------------------------------- 1 | // Calculates the area of a circle 2 | // @Author: Adam Janecka 3 | package pkg10_13; 4 | 5 | public class Circle extends TwoDimensionalShape{ 6 | 7 | private double radius; // radius of the circle 8 | 9 | // constructor 10 | public Circle(double radius) 11 | { 12 | if (radius < 0) 13 | throw new IllegalArgumentException 14 | ("Radius must be < 0"); 15 | 16 | this.radius = radius; 17 | } // end constructor 18 | 19 | // Sets the radius 20 | public void setRadius(double radius) 21 | { 22 | if (radius < 0) 23 | throw new IllegalArgumentException 24 | ("Radius must be < 0"); 25 | this.radius = radius; 26 | } // end method setRadius 27 | 28 | // Returns radius 29 | public double getRadius() 30 | { 31 | return radius; 32 | } // end method getRadius 33 | 34 | // Calculates Area 35 | @Override 36 | public double getArea() 37 | { 38 | return getRadius() * getRadius() * Math.PI; 39 | } // end method getArea 40 | 41 | // toString method 42 | @Override 43 | public String toString() 44 | { 45 | return String.format("%s %s%n%s: %.2f", super.toString(), "Circle", 46 | "Radius", getRadius()); 47 | } // end method toString 48 | } // end class Circle 49 | -------------------------------------------------------------------------------- /Chapter10/Exercises/10.13/Cube.java: -------------------------------------------------------------------------------- 1 | // Calculates volume and surface area of cube 2 | // @Author: Adam Janecka 3 | package pkg10_13; 4 | 5 | public class Cube extends ThreeDimensionalShape{ 6 | 7 | private double length; // Length of a side of the cube 8 | 9 | // constructor 10 | public Cube(double length) 11 | { 12 | if (length < 0) 13 | throw new IllegalArgumentException 14 | ("Length must be > 0"); 15 | 16 | this.length = length; 17 | } // end constructor 18 | 19 | // sets value of length 20 | public void setLength(double length) 21 | { 22 | if (length < 0) 23 | throw new IllegalArgumentException 24 | ("Length must be > 0"); 25 | this.length = length; 26 | } // end method setLength 27 | 28 | // returns value of length 29 | public double getLength() 30 | { 31 | return length; 32 | } // end method getLength 33 | 34 | // calculates surface area 35 | @Override 36 | public double getArea() 37 | { 38 | return getLength() * getLength() * 6; 39 | } // end method getArea 40 | 41 | // calculates volume 42 | @Override 43 | public double getVolume() 44 | { 45 | return getLength() * getLength() * getLength(); 46 | } // end method getVolume 47 | 48 | // toString Method 49 | @Override 50 | public String toString() 51 | { 52 | return String.format("%s: %s%n%s: %.2f", 53 | super.toString(), "Cube", "Length", getLength()); 54 | } // end method toString 55 | } // end class Cube 56 | -------------------------------------------------------------------------------- /Chapter10/Exercises/10.13/Shape.java: -------------------------------------------------------------------------------- 1 | // Abstract superclass at top of hierarchy 2 | // @Author: Adam Janecka 3 | package pkg10_13; 4 | 5 | public abstract class Shape { 6 | 7 | // Both 2D and 3D shapes will have the getArea method 8 | public abstract double getArea(); 9 | } // end class Shape 10 | -------------------------------------------------------------------------------- /Chapter10/Exercises/10.13/Square.java: -------------------------------------------------------------------------------- 1 | // Finds area for square 2 | // @Author: Adam Janecka 3 | package pkg10_13; 4 | 5 | public class Square extends TwoDimensionalShape{ 6 | 7 | private double length; // Length of side 8 | 9 | // constructor 10 | public Square(double length) 11 | { 12 | if(length < 0) 13 | throw new IllegalArgumentException 14 | ("Length must be > 0"); 15 | 16 | this.length = length; 17 | } // end constructor 18 | 19 | // set length 20 | public void setLength(double length) 21 | { 22 | if (length < 0) 23 | throw new IllegalArgumentException 24 | ("Length must be > 0"); 25 | this.length = length; 26 | } // end method setLength 27 | 28 | // get length 29 | public double getLength() 30 | { 31 | return length; 32 | } // end method getLength 33 | 34 | // Calculates area 35 | @Override 36 | public double getArea() 37 | { 38 | return getLength() * getLength(); 39 | } // end method getArea 40 | 41 | // toString method 42 | @Override 43 | public String toString() 44 | { 45 | return String.format("%s %s%n%s: %.2f", super.toString(), "Square", 46 | "Length", getLength()); 47 | } // end method toString 48 | } // end class Square 49 | -------------------------------------------------------------------------------- /Chapter10/Exercises/10.13/ThreeDimensionalShape.java: -------------------------------------------------------------------------------- 1 | // Superclass for three dimensional shapes 2 | // @Author: Adam Janecka 3 | package pkg10_13; 4 | 5 | public abstract class ThreeDimensionalShape extends Shape{ 6 | 7 | public abstract double getVolume(); // calculates volume 8 | 9 | // toString Method 10 | @Override 11 | public String toString() 12 | { 13 | return String.format("Three Dimensional Shape"); 14 | } // end method toString 15 | 16 | } // end class ThreeDimensionalShape 17 | -------------------------------------------------------------------------------- /Chapter10/Exercises/10.13/TwoDimensionalShape.java: -------------------------------------------------------------------------------- 1 | // Superclass for two-dimensional shapes 2 | // @Author: Adam Janecka 3 | package pkg10_13; 4 | 5 | public abstract class TwoDimensionalShape extends Shape{ 6 | 7 | // toString override 8 | @Override 9 | public String toString() 10 | { 11 | return String.format("Two dimensional shape:"); 12 | } // end method toString 13 | } // end class TwoDimensionalShape 14 | -------------------------------------------------------------------------------- /Chapter11/Examples/11.02/DivideByZeroNoExceptionHandling.java: -------------------------------------------------------------------------------- 1 | // Fig. 11.2: DivideByZeroNoExceptionHandling.java 2 | // Integer division without exception handling 3 | package pkg11_02; 4 | import java.util.Scanner; 5 | 6 | public class DivideByZeroNoExceptionHandling { 7 | 8 | // demonstrates throwing an exception when a divide-by-zero occurs 9 | public static int quotient(int numerator, int denominator) 10 | { 11 | return numerator / denominator; // possible division by zero 12 | } // end method quotient 13 | 14 | public static void main(String[] args) { 15 | 16 | Scanner scanner = new Scanner(System.in); 17 | System.out.print("Please enter an integer numerator: "); 18 | int numerator = scanner.nextInt(); 19 | System.out.print("Please enter an integer denominator: "); 20 | int denominator = scanner.nextInt(); 21 | 22 | int result = quotient(numerator, denominator); 23 | System.out.printf( 24 | "%nResult: %d / %d = %d%n", numerator, denominator, result); 25 | } // end method main 26 | } // end class DivideByZeroNoExceptionHandling 27 | -------------------------------------------------------------------------------- /Chapter11/Examples/11.07/UsingChainedExceptions.java: -------------------------------------------------------------------------------- 1 | // Fig. 11.7: UsingChainedExceptions.java 2 | // Chained exceptions. 3 | package pkg11_07; 4 | 5 | public class UsingChainedExceptions { 6 | 7 | public static void main(String[] args) { 8 | 9 | try{ 10 | method1(); 11 | } 12 | catch(Exception exception) // exceptions thrown from method1 13 | { 14 | exception.printStackTrace(); 15 | } 16 | } // end method main 17 | 18 | // call method2; throw excpetions back to main 19 | public static void method1() throws Exception 20 | { 21 | try 22 | { 23 | method2(); 24 | } // end try 25 | catch(Exception exception) // exception thrown from method2 26 | { 27 | throw new Exception("Exception thrown in method1", exception); 28 | } 29 | } // end method1 30 | 31 | // call method3; throw exceptions back to method1 32 | public static void method2() throws Exception 33 | { 34 | try 35 | { 36 | method3(); 37 | } 38 | catch(Exception exception) // exception thrown from method3 39 | { 40 | throw new Exception("Exception thrown in method2", exception); 41 | } 42 | } // end method2 43 | 44 | // throw Exception back to method2 45 | public static void method3() throws Exception 46 | { 47 | throw new Exception("Exception thrown in method3"); 48 | } // end method3 49 | } // end class UsingChainedExceptions 50 | -------------------------------------------------------------------------------- /Chapter11/Examples/11.08/AssertTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 11.8: AssertTest.java 2 | // Checking with assert that a value is within range 3 | package pkg11_08; 4 | import java.util.Scanner; 5 | 6 | public class AssertTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | System.out.print("Enter a number between 0 and 10: "); 13 | int number = input.nextInt(); 14 | 15 | // assert that the value is >= 0 and <= 10 16 | assert (number >= 0 && number <= 10) : "bad number: " + number; 17 | 18 | System.out.printf("You entered %d%n", number); 19 | } // end method main 20 | } // end class AssertTest 21 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.01/StringConstructors.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.1: StringConstructors.java 2 | // String class constructors 3 | package pkg14_01; 4 | 5 | public class StringConstructors { 6 | 7 | public static void main(String[] args) { 8 | 9 | char[] charArray = {'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y'}; 10 | String s = new String("hello"); 11 | 12 | // use String constructors 13 | String s1 = new String(); 14 | String s2 = new String(s); 15 | String s3 = new String(charArray); 16 | String s4 = new String(charArray, 6, 3); 17 | 18 | System.out.printf( 19 | "s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n", s1, s2, s3, s4); 20 | } // end method main 21 | } // end class StringConstructors 22 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.02/StringMiscellaneous.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.2: StringMiscellaneous.java 2 | // This application demonstrates the length, charAt and getChars 3 | // methods of the String class 4 | package pkg14_02; 5 | 6 | public class StringMiscellaneous { 7 | 8 | public static void main(String[] args) { 9 | 10 | String s1 = "hello there"; 11 | char[] charArray = new char[5]; 12 | 13 | System.out.printf("s1: %s", s1); 14 | 15 | // test length method 16 | System.out.printf("%nLength of s1: %d", s1.length()); 17 | 18 | // loop through characters in s1 with charAt and display reversed 19 | System.out.printf("%nThe string reversed is: "); 20 | 21 | for (int count = s1.length() - 1; count >= 0; count--) 22 | System.out.printf("%c ", s1.charAt(count)); 23 | 24 | // copy characters from string into charArray 25 | s1.getChars(0, 5, charArray, 0); 26 | System.out.printf("%nThe character array is: "); 27 | 28 | for (char character : charArray) 29 | System.out.print(character); 30 | 31 | System.out.println(); 32 | } // end method main 33 | } // end class StringMiscellaneous 34 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.04/StringStartEnd.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.4: StringStartEnd.java 2 | // String methods startsWith and endsWith 3 | package pkg14_04; 4 | 5 | public class StringStartEnd { 6 | 7 | public static void main(String[] args) { 8 | 9 | String[] strings = {"started", "starting", "ended", "ending"}; 10 | 11 | // test method startsWith 12 | for (String string : strings) 13 | { 14 | if (string.startsWith("st")) 15 | System.out.printf("\"%s\" starts with \"st\"%n", string); 16 | } 17 | 18 | System.out.println(); 19 | 20 | // test method startsWith starting from position 2 of string 21 | for (String string : strings) 22 | { 23 | if (string.startsWith("art", 2)) 24 | System.out.printf( 25 | "\"%s\" starts with \"art\" at poition 2%n", string); 26 | } 27 | 28 | System.out.println(); 29 | 30 | // test method endsWith 31 | for (String string : strings) 32 | { 33 | if (string.endsWith("ed")) 34 | System.out.printf("\"%s\" ends with \"ed\"%n", string); 35 | } 36 | } // end method main 37 | } // end class StringStartEnd 38 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.06/SubString.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.6: SubString.java 2 | // String class substring methods 3 | package pkg14_06; 4 | 5 | public class SubString { 6 | 7 | public static void main(String[] args) { 8 | 9 | String letters = "abcdefghijklmabcdefghijklm"; 10 | 11 | // test substring methods 12 | System.out.printf("Substring from index 20 to end is \"%s\"%n", 13 | letters.substring(20)); 14 | System.out.printf("%s \"%s\"%n", 15 | "Substring from index 3 up to, but not including 6 is", 16 | letters.substring(3, 6)); 17 | } // end method main 18 | } // end class SubString 19 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.07/StringConcatenation.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.7: StringConcatenation.java 2 | // String method concat 3 | package pkg14_07; 4 | 5 | public class StringConcatenation { 6 | 7 | public static void main(String[] args) { 8 | 9 | String s1 = "Happy "; 10 | String s2 = "Birthday"; 11 | 12 | System.out.printf("s1 = %s%ns2 = %s%n%n", s1, s2); 13 | System.out.printf( 14 | "Result of s1.concat(s2) = %s%n", s1.concat(s2)); 15 | System.out.printf("s1 after concatenation = %s%n", s1); 16 | } // end method main 17 | } // end class StringConcatenation 18 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.08/StringMiscellaneous2.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.8: StringMiscellaneous2.java 2 | // String methods replace, toLowerCase, toUpperCase, trim and toCharArray 3 | package pkg14_08; 4 | 5 | public class StringMiscellaneous2 { 6 | 7 | public static void main(String[] args) { 8 | 9 | String s1 = "hello"; 10 | String s2 = "GOODBYE"; 11 | String s3 = " spaces "; 12 | 13 | System.out.printf("s1 = %s%ns2 = %s%ns3 = %s%n%n", s1, s2, s3); 14 | 15 | // test method replace 16 | System.out.printf( 17 | "Replace 'l' with 'L' in s1: %s%n%n", s1.replace('l', 'L')); 18 | 19 | // test toLowerCase and toUpperCase 20 | System.out.printf("s1.toUpperCase() = %s%n", s1.toUpperCase()); 21 | System.out.printf("s2.toLowerCase() = %s%n%n", s2.toLowerCase()); 22 | 23 | // test trim method 24 | System.out.printf("s3 after trim = \"%s\"%n%n", s3.trim()); 25 | 26 | // test toCharArray method 27 | char[] charArray = s1.toCharArray(); 28 | System.out.print("s1 as a character array = "); 29 | 30 | for (char character : charArray) 31 | System.out.print(character); 32 | 33 | System.out.println(); 34 | } // end method main 35 | } // end class StringMiscellaneous2 36 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.09/StringValueOf.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.9: StringValueOf.java 2 | // String valueOf methods 3 | package pkg14_09; 4 | 5 | public class StringValueOf { 6 | 7 | public static void main(String[] args) { 8 | 9 | char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; 10 | boolean booleanValue = true; 11 | char characterValue = 'Z'; 12 | int integerValue = 7; 13 | long longValue = 10000000000L; // L suffix indicates long 14 | float floatValue = 2.5f; // f indicates that 2.5 is a flot 15 | double doubleValue = 33.333; // no suffix, double is default 16 | Object objectRef = "hello"; // assign string to an Object reference 17 | 18 | System.out.printf( 19 | "char array = %s%n", String.valueOf(charArray)); 20 | System.out.printf("part of char array = %s%n", 21 | String.valueOf(charArray, 3, 3)); 22 | System.out.printf( 23 | "boolean = %s%n", String.valueOf(booleanValue)); 24 | System.out.printf( 25 | "char = %s%n", String.valueOf(characterValue)); 26 | System.out.printf( 27 | "int = %s%n", String.valueOf(integerValue)); 28 | System.out.printf( 29 | "long = %s%n", String.valueOf(longValue)); 30 | System.out.printf( 31 | "float = %s%n", String.valueOf(floatValue)); 32 | System.out.printf( 33 | "double = %s%n", String.valueOf(doubleValue)); 34 | System.out.printf("Object = %s", String.valueOf(objectRef)); 35 | } // end method main 36 | } // end class StringValueOf 37 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.10/StringBuilderConstructors.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.10: Strng Builder Constructors.java 2 | // StringBuilder constructors 3 | package pkg14_10; 4 | 5 | public class StringBuilderConstructors { 6 | 7 | public static void main(String[] args) { 8 | 9 | StringBuilder buffer1 = new StringBuilder(); 10 | StringBuilder buffer2 = new StringBuilder(10); 11 | StringBuilder buffer3 = new StringBuilder("hello"); 12 | 13 | System.out.printf("buffer1 = \"%s\"%n", buffer1); 14 | System.out.printf("buffer2 = \"%s\"%n", buffer2); 15 | System.out.printf("buffer3 = \"%s\"%n", buffer3); 16 | } // end method main 17 | } // end class StringBuilderConstructors 18 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.11/StringBuilderCapLen.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.11: StringBuilderCapLen.java 2 | // StringBuilder length, setLength, capacity and ensureCapacity methods. 3 | package pkg14_11; 4 | 5 | public class StringBuilderCapLen { 6 | 7 | public static void main(String[] args) { 8 | 9 | StringBuilder buffer = new StringBuilder("Hello, how are you?"); 10 | 11 | System.out.printf("buffer = %s%nlength = %d%ncapacity = %d%n%n", 12 | buffer.toString(), buffer.length(), buffer.capacity()); 13 | 14 | buffer.ensureCapacity(75); 15 | System.out.printf("New capacity = %d%n%n", buffer.capacity()); 16 | 17 | buffer.setLength(10); 18 | System.out.printf("New length = %d%nbuffer = %s%n", 19 | buffer.length(), buffer.toString()); 20 | } // end method main 21 | } // end class StringBuilderCapLen 22 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.12/StringBuilderChars.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.12: StringBuilderChars.java 2 | // StringBuilder methods charAt, setCharAt, getChars and reverse 3 | package pkg14_12; 4 | 5 | public class StringBuilderChars { 6 | 7 | public static void main(String[] args) { 8 | 9 | StringBuilder buffer = new StringBuilder("hello there"); 10 | 11 | System.out.printf("buffer = %s%n", buffer.toString()); 12 | System.out.printf("Character at 0: %s%nCharacter at 4: %s%n%n", 13 | buffer.charAt(0), buffer.charAt(4)); 14 | 15 | char[] charArray = new char[buffer.length()]; 16 | buffer.getChars(0, buffer.length(), charArray, 0); 17 | System.out.print("The characters are: "); 18 | 19 | for (char character : charArray) 20 | System.out.print(character); 21 | 22 | buffer.setCharAt(0, 'H'); 23 | buffer.setCharAt(6, 'T'); 24 | System.out.printf("%n%nbuffer = %s", buffer.toString()); 25 | 26 | buffer.reverse(); 27 | System.out.printf("%n%nbuffer = %s%n", buffer.toString()); 28 | } // end method main 29 | } // end class StringBuilderChars 30 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.15/StaticCharMethods.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.15: StaticCharMethods.java 2 | // Character static methods for testing characters and converting case 3 | package pkg14_15; 4 | import java.util.Scanner; 5 | 6 | public class StaticCharMethods { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner scanner = new Scanner(System.in); // create Scanner 11 | System.out.println("enter a character and press Enter"); 12 | String input = scanner.next(); 13 | char c = input.charAt(0); // get input character 14 | 15 | // display character info 16 | System.out.printf("is defined: %b%n", Character.isDefined(c)); 17 | System.out.printf("is digit: %b%n", Character.isDigit(c)); 18 | System.out.printf("is first charcter in a Java identifier: %b%n", 19 | Character.isJavaIdentifierStart(c)); 20 | System.out.printf("is letter: %b%n", Character.isLetter(c)); 21 | System.out.printf( 22 | "is letter or digit: %b%n", Character.isLetterOrDigit(c)); 23 | System.out.printf( 24 | "is lower case: %b%n", Character.isLowerCase(c)); 25 | System.out.printf( 26 | "is upper case: %b%n", Character.isUpperCase(c)); 27 | System.out.printf( 28 | "to upper case %s%n", Character.toUpperCase(c)); 29 | System.out.printf( 30 | "to lower case: %s%n", Character.toLowerCase(c)); 31 | } // end method main 32 | } // end class StaticCharMethods 33 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.16/StaticCharMethods2.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.16: StaticCharMethods2.java 2 | // Character class static conversion methods 3 | package pkg14_16; 4 | import java.util.Scanner; 5 | 6 | public class StaticCharMethods2 { 7 | 8 | // executes application 9 | public static void main(String[] args) { 10 | 11 | Scanner scanner = new Scanner(System.in); 12 | 13 | // get radix 14 | System.out.println("Please enter a radix:"); 15 | int radix = scanner.nextInt(); 16 | 17 | // get user choice 18 | System.out.printf("Please choose one:%n1 -- %s%n2 -- %s%n", 19 | "Convert digit to character", "Convert character to digit"); 20 | int choice = scanner.nextInt(); 21 | 22 | // process request 23 | switch(choice) 24 | { 25 | case 1: // convert digit to character 26 | System.out.println("Enter a digit:"); 27 | int digit = scanner.nextInt(); 28 | System.out.printf("Convert digit to character: %s%n", 29 | Character.forDigit(digit, radix)); 30 | break; 31 | case 2: // convert character to digit 32 | System.out.println("Enter a character:"); 33 | char character = scanner.next().charAt(0); 34 | System.out.printf("Convert character to digit: %s%n", 35 | Character.digit(character,radix)); 36 | break; 37 | } 38 | } // end method main 39 | } // end class StaticCharMethods2 40 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.17/OtherCharMethods.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.17: OtherCharMethods.java 2 | // Character class instance methods 3 | package pkg14_17; 4 | 5 | public class OtherCharMethods { 6 | 7 | public static void main(String[] args) { 8 | 9 | Character c1 = 'A'; 10 | Character c2 = 'a'; 11 | 12 | System.out.printf( 13 | "c1 = %s%nc2 = %s%n%n", c1.charValue(), c2.toString()); 14 | 15 | if(c1.equals(c2)) 16 | System.out.println("c1 and c2 are equal%n"); 17 | else 18 | System.out.println("c1 and c2 are not equal%n"); 19 | } // end method main 20 | } // end class OtherCharMethods 21 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.18/TokenTest.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.18: TokenTest.java 2 | // StringTokenizer obect used to tokenize strings 3 | package pkg14_18; 4 | import java.util.Scanner; 5 | import java.util.StringTokenizer; 6 | 7 | public class TokenTest { 8 | 9 | // execute application 10 | public static void main(String[] args) { 11 | 12 | // get sentence 13 | Scanner scanner = new Scanner(System.in); 14 | 15 | System.out.println("Enter a sentence and press Enter"); 16 | String sentence = scanner.nextLine(); 17 | 18 | //process user sentence 19 | String[] tokens = sentence.split(" "); 20 | System.out.printf("Number of elements: %d%nThe tokens are:%n", 21 | tokens.length); 22 | 23 | for (String token: tokens) 24 | System.out.println(token); 25 | } // end method main 26 | } // end class TokenTest 27 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.20/ValidateInput.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.20: ValidateInput.java 2 | // Validating user information using regular expressions 3 | package pkg14_20; 4 | 5 | public class ValidateInput { 6 | 7 | // validate first name 8 | public static boolean validateFirstName(String firstName) 9 | { 10 | return firstName.matches("[A-Z][a-zA-Z]*"); 11 | } 12 | 13 | // validate last name 14 | public static boolean validateLastName(String lastName) 15 | { 16 | return lastName.matches("[a-zA-Z]+(['-][a-zA-z]+)*"); 17 | } 18 | 19 | // validate address 20 | public static boolean validateAddress(String address) 21 | { 22 | return address.matches( 23 | "\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)"); 24 | } 25 | 26 | // validate city 27 | public static boolean validateCity(String city) 28 | { 29 | return city.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)"); 30 | } 31 | 32 | // validate state 33 | public static boolean validateState(String state) 34 | { 35 | return state.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)"); 36 | } 37 | 38 | // validate zip 39 | public static boolean validateZip(String zip) 40 | { 41 | return zip.matches("\\d{5}"); 42 | } 43 | 44 | // validate phone 45 | public static boolean validatePhone(String phone) 46 | { 47 | return phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}"); 48 | } 49 | } // end class ValidateInput 50 | -------------------------------------------------------------------------------- /Chapter14/Examples/14.24/RegexMatches.java: -------------------------------------------------------------------------------- 1 | // Fig. 14.24: RegexMatches.java 2 | // Classes Pattern and Matcher. 3 | package pkg14_24; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class RegexMatches { 8 | 9 | public static void main(String[] args) { 10 | 11 | // create regular expression 12 | Pattern expression = 13 | Pattern.compile("J.*\\d[0-35-9]-\\d\\d-\\d\\d"); 14 | 15 | String string1 = "Jane's Birthday is 05-12-75\n" + 16 | "Dave's Birthday is 11-04-68\n" + 17 | "John's Birthday is 04-28-73\n" + 18 | "Joe's Birthday is 12-17-77"; 19 | 20 | // match regular expression to string and print matches 21 | Matcher matcher = expression.matcher(string1); 22 | 23 | while(matcher.find()) 24 | System.out.println(matcher.group()); 25 | } // end method main 26 | } // end class RegexMatches 27 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.03/CompareTo.java: -------------------------------------------------------------------------------- 1 | // Inputs two Strings and outputs whether the first is less then, equal to 2 | // or greater than the second 3 | // @Author: Adam Janecka 4 | package pkg14_03; 5 | import java.util.Scanner; 6 | 7 | public class CompareTo { 8 | 9 | public static void main(String[] args) { 10 | 11 | Scanner input = new Scanner(System.in); 12 | 13 | String word1; // First string 14 | String word2; // Second string 15 | 16 | // Obtain Strings 17 | System.out.print("Enter first string: "); 18 | word1 = input.nextLine(); 19 | System.out.print("Enter second string: "); 20 | word2 = input.nextLine(); 21 | 22 | // Determine relationship between strings 23 | if (word1.compareTo(word2) == 0) 24 | System.out.println("The strings are equal."); 25 | else if (word1.compareTo(word2) < 0) 26 | System.out.println("The first string is less than the second string."); 27 | else 28 | System.out.println("The first string is greater than the second string."); 29 | } // end method main 30 | } // end class CompareTo 31 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.04/ComparePortions.java: -------------------------------------------------------------------------------- 1 | // Sees if portions of two strings are equal 2 | // @Author: Adam Janecka 3 | package pkg14_04; 4 | import java.util.Scanner; 5 | 6 | public class ComparePortions { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | 12 | String s1; // First string 13 | String s2; // Second string 14 | 15 | // Inputs strings 16 | System.out.print("Enter first string: "); 17 | s1 = input.nextLine(); 18 | System.out.print("Enter second string: "); 19 | s2 = input.nextLine(); 20 | 21 | // Select portion of strings to compare 22 | System.out.print("Enter number of characters to compare: "); 23 | int num = input.nextInt(); 24 | System.out.print("Enter starting index of first string: "); 25 | int index1 = input.nextInt(); 26 | System.out.print("Enter starting index of second string: "); 27 | int index2 = input.nextInt(); 28 | 29 | if (s1.regionMatches(true, index1, s2, index2, num)) 30 | System.out.println("The portion of the two strings are equal."); 31 | } // end method main 32 | } // end class ComparePortions 33 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.07/PigLatin.java: -------------------------------------------------------------------------------- 1 | // Translate sentences into Pig Latin 2 | // @Author: Adam Janecka 3 | package pkg14_07; 4 | import java.util.Scanner; 5 | import java.util.StringTokenizer; 6 | 7 | public class PigLatin { 8 | 9 | public static void main(String[] args) { 10 | 11 | String sentence; 12 | int count ; // iterates through sentence 13 | Scanner input = new Scanner(System.in); 14 | 15 | // Enter sentence 16 | System.out.println("Enter sentence: "); 17 | sentence = input.nextLine(); 18 | 19 | // Split into tokens 20 | StringTokenizer tokens = new StringTokenizer(sentence); 21 | count = tokens.countTokens(); 22 | while(tokens.hasMoreTokens()) 23 | { 24 | count--; 25 | printLatinWord(tokens.nextToken()); 26 | } 27 | System.out.println(); 28 | } // end method main 29 | 30 | // translates English word into Pig Latin 31 | public static void printLatinWord(String token) 32 | { 33 | char letters[] = token.toCharArray(); 34 | String translation = new String(); 35 | 36 | for (int i = 1; i < letters.length; i++) 37 | { 38 | translation += letters[i]; 39 | } 40 | 41 | translation += letters[0] + "ay "; 42 | System.out.print(translation); 43 | } // end method printLatinWord 44 | } // end class PigLatin 45 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.08/PhoneNumber.java: -------------------------------------------------------------------------------- 1 | // Inputs phone number and outputs phone number using String tokenization 2 | // @Author: Adam Janecka 3 | package pkg14_08; 4 | import java.util.Scanner; 5 | 6 | public class PhoneNumber { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | String phone; // Full phone number 12 | String areaCode; 13 | String token1; 14 | String token2; 15 | String[] phoneNumber = new String[2]; 16 | String[] phoneNumber2 = new String[2]; 17 | 18 | 19 | System.out.print("Enter phone number as (xxx) xxx-xxxx: "); 20 | phone = input.nextLine(); 21 | 22 | // split to obtain area code 23 | phoneNumber = phone.split(" "); 24 | areaCode = phoneNumber[0].substring(1,4); 25 | 26 | // Split remaining to obtain 555-5555 27 | phoneNumber2 = phoneNumber[1].split("-"); 28 | token1 = phoneNumber2[0]; 29 | token2 = phoneNumber2[1]; 30 | 31 | System.out.printf("Area Code: %s", areaCode); 32 | System.out.printf("%nPhone Number: %s%s%n", token1, token2); 33 | 34 | } // end method main 35 | } // end class PhoneNumber 36 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.09/ReverseWords.java: -------------------------------------------------------------------------------- 1 | // Prints the words out in reverse order 2 | // @Author: Adam Janecka 3 | package pkg14_09; 4 | import java.util.Scanner; 5 | 6 | public class ReverseWords { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | String sentence; 12 | String[] tokens; 13 | 14 | // Obtain sentence 15 | System.out.print("Enter sentence: "); 16 | sentence = input.nextLine(); 17 | tokens = sentence.split(" "); 18 | 19 | // Print out sentence backwards 20 | for (int i = tokens.length - 1; i >= 0; i--) 21 | { 22 | System.out.print(tokens[i] + " "); 23 | } 24 | System.out.println(); 25 | } // end method main 26 | } // end class ReverseWords 27 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.10/BothCases.java: -------------------------------------------------------------------------------- 1 | // Prints out a string in all uppercase and all lowercase 2 | // @Author: Adam Janecka 3 | package pkg14_10; 4 | import java.util.Scanner; 5 | 6 | public class BothCases { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | String sentence; 12 | 13 | // Obtain sentence 14 | System.out.print("Enter sentence: "); 15 | sentence = input.nextLine(); 16 | 17 | System.out.printf("Sentence as uppercase: %s%nSentence as lowercase: %s%n", 18 | sentence.toUpperCase(), sentence.toLowerCase()); 19 | } // end method main 20 | } // end class BothCases 21 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.11/StringSearch.java: -------------------------------------------------------------------------------- 1 | // Shows the number of occurences of a character 2 | // @Author: Adam Janecka 3 | package pkg14_11; 4 | import java.util.Scanner; 5 | 6 | public class StringSearch { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | String sentence; 12 | int index = 0; 13 | int count = 0; // Number of occurences of character 14 | String c; // Character to search for 15 | 16 | // Obtain sentence 17 | System.out.print("Enter sentence: "); 18 | sentence = input.nextLine(); 19 | System.out.print("Enter search character: "); 20 | c = input.nextLine(); 21 | 22 | while(index <= sentence.length()) 23 | { 24 | index = sentence.indexOf(c, index); 25 | 26 | if (index >= 0) 27 | { 28 | index++; 29 | count++; 30 | } 31 | else 32 | break; 33 | } 34 | 35 | System.out.printf("Number of occurences of %s: %d%n", c, count); 36 | } // end method main 37 | } // end classStringSearch 38 | -------------------------------------------------------------------------------- /Chapter14/Exercises/14.12/StringSearch2.java: -------------------------------------------------------------------------------- 1 | // Shows the occurences of all letters in a sentence 2 | // @Author: Adam Janecka 3 | package pkg14_12; 4 | import java.util.Scanner; 5 | 6 | public class StringSearch2 { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner input = new Scanner(System.in); 11 | String alphabet = "abcdefghijklmnopqrstuvwxyz"; 12 | int[] count = new int[26]; 13 | String line; 14 | int index = 0; 15 | 16 | // Obtain sentence 17 | System.out.print("Enter sentence: "); 18 | line = input.nextLine(); 19 | 20 | for (int i = 0; i <= 25; i++) 21 | { 22 | while (index <= line.length()) 23 | { 24 | index = line.indexOf(alphabet.charAt(i), index); 25 | 26 | if (index >= 0) 27 | { 28 | index++; 29 | count[i]++; 30 | } 31 | else 32 | break; 33 | } 34 | } 35 | 36 | System.out.print("Letter occurences: \n"); 37 | for(int j = 0; j <= 25; j++) 38 | { 39 | System.out.printf("%c: %d%n", alphabet.charAt(j), count[j]); 40 | } 41 | } // end method main 42 | } // end class StringSearch2 43 | --------------------------------------------------------------------------------