├── README.md ├── Chapter 2- Primitive Data and Definite Loops ├── Self-Check 2.2: evaluatingExpressions.java ├── Self-Check 2.12: valueOfX.java ├── Self-Check 2.1: legalIntLiterals.java ├── Self-Check 2.23: completeLoop.java ├── Exercise 2.5: starTriangle.java ├── Exercise 2.4: starSquare.java ├── Exercise 2.7: spacedNumbers.java ├── Exercise 2.6: numberTriangle .java ├── Self-Check 2.14: firstSecond.java ├── Self-Check 2.27: howManyLines .java ├── Self-Check 2.16: valuesOfIJK.java ├── Self-Check 2.28: blastOff.java ├── Self-Check 2.13: valuesOfABC.java ├── Self-Check 2.9: lastDigitExpression.java ├── Self-Check 2.24: oddStuff.java ├── Exercise 2.8: spacesAndNumbers.java ├── Self-Check 2.25: numberTotal.java ├── Self-Check 2.6: declareRealNumberSyntax.java ├── Self-Check 2.26: fingerTrap.java ├── Self-Check 2.17: maxMin.java ├── Self-Check 2.32: starExclamation2.java ├── Self-Check 2.31: starExclamation1.java ├── Exercise 2.12: nestedNumbers.java ├── Exercise 2.2: loopSquares .java ├── Self-Check 2.33: starExclamation3.java ├── Self-Check 2.29: multiplication.java ├── Self-Check 2.18: timesOperator.java ├── Self-Check 2.21: Count2.java ├── Self-Check 2.11: digitExpressions.java ├── Self-Check 2.15: firstSecond2.java ├── Self-Check 2.7: fitnessVariables.java ├── Self-Check 2.8: studentVariables.java ├── Exercise 2.14: nestedNumbers3.java ├── Self-Check 2.35: unknown.java ├── Exercise 2.13: nestedNumbers2.java ├── Self-Check 2.36: loopTableConstant.java ├── Exercise 2.10: numbersOutput60.java ├── Exercise 2.15: printDesign.java ├── Self-Check 2.30: nestedLoops.java ├── Exercise 2.9: waveNumbers40.java ├── Exercise 2.1: displacement.java ├── Exercise 2.20: StarFigure.java ├── Exercise 2.3: fibonacci.java ├── Self-Check 2.37: loopTableSlashes .java ├── Exercise 2.18: pseudocodeWindow.java ├── Exercise 2.16: SlashFigure.java ├── Exercise 2.22: DollarFigure.java ├── Self-Check 2.10: Oops2-errors.java ├── Self-Check 2.22: loopTable.java ├── Self-Check 2.5: expressions3.java ├── Self-Check 2.3: expressions1.java ├── Self-Check 2.4: expressions2.java ├── Exercise 2.21: StarFigure2.java ├── Exercise 2.11: numbersOutputConstant.java └── Exercise 2.23: DollarFigure2.java ├── Chapter 1- Introduction to Java Programming ├── Self-Check 1.15: printlnSlashes.java ├── Self-Check 1.2: binary1.java ├── Self-Check 1.3: binary2.java ├── Self-Check 1.10: Shaq.java ├── Self-Check 1.8: confounding.java ├── Self-Check 1.21: methodHeaderSyntax.java ├── Self-Check 1.4: cookieRecipe.java ├── Self-Check 1.7: outputSyntax.java ├── Self-Check 1.13: Sally.java ├── Self-Check 1.6: legalIdentifiers.java ├── Self-Check 1.9: Archie.java ├── Self-Check 1.11: downwardSpiral.java ├── Exercise 1.1: Stewie.java ├── Self-Check 1.19: SecretMessage-errors.java ├── Exercise 1.2: Spikey.java ├── Self-Check 1.18: MyProgram-errors.java ├── Exercise 1.9: Egg.java ├── Self-Check 1.14: TestOfKnowledge.java ├── Self-Check 1.1: binaryNumbers.java ├── Self-Check 1.16: withoutPrintStatements.java ├── Exercise 1.4: Difference.java ├── Self-Check 1.22: Tricky.java ├── Self-Check 1.12: DoubleSlash.java ├── Exercise 1.7: Mantra.java ├── Exercise 1.5: MuchBetter.java ├── Exercise 1.3: WellFormed.java ├── Self-Check 1.29: LotsOfErrors-errors.java ├── Self-Check 1.26: Confusing.java ├── Self-Check 1.5: javaVsClass.java ├── Exercise 1.6: Meta.java ├── Self-Check 1.17: Commentary.java ├── Exercise 1.8: Stewie2.java ├── Self-Check 1.28: Confusing3.java ├── Self-Check 1.27: Confusing2.java ├── Self-Check 1.23: Strange.java ├── Self-Check 1.25: Strange3.java ├── Self-Check 1.24: Strange2.java ├── Exercise 1.13: StarFigures.java ├── Exercise 1.15: EggStop.java ├── Self-Check 1.32: Messy.java └── Exercise 1.10: Egg2.java ├── Chapter 7- Arrays ├── Self-Check 7.9: declareArray.java ├── Self-Check 7.3: dataArray.java ├── Self-Check 7.34: copyColumn.java ├── Self-Check 7.4: oddsArray.java ├── Self-Check 7.32: rectangularArray.java ├── Self-Check 7.1: arrayDeclarationSyntax.java ├── Self-Check 7.14: arrayCodeTracing2.java ├── Self-Check 7.16a: countStrings.java ├── Self-Check 7.2: numbersElements.java ├── Self-Check 7.5: numbersArray.java ├── Self-Check 7.33: fiveByTenArray.java ├── Self-Check 7.6: fillDataArray.java ├── Self-Check 7.8: arrayDeclarationSyntax2.java ├── Self-Check 7.22: arrayCodeTracing3.java ├── Self-Check 7.23: arrayCodeTracing4.java ├── Self-Check 7.15: printBackwards.java ├── Self-Check 7.24: arrayMystery1.java ├── Self-Check 7.18: arraySwap.java ├── Exercise 7.1: lastIndexOf.java ├── Self-Check 7.29: averageLength.java ├── Self-Check 7.10: max.java ├── Self-Check 7.25: arrayMystery2.java ├── Self-Check 7.31: arrayCodeTracing2d.java ├── Self-Check 7.13: printElements.java ├── Self-Check 7.26: arrayMystery3.java ├── Self-Check 7.27: arrayMystery4.java ├── Exercise 7.3: countInRange.java ├── Self-Check 7.16b: equalsStrings.java ├── Exercise 7.10: percentEven.java ├── Self-Check 7.28: arrayMystery5.java ├── Self-Check 7.30: isPalindrome.java ├── Self-Check 7.11: average.java ├── Exercise 7.4: isSorted.java ├── Self-Check 7.17: allLess.java ├── Exercise 7.7: kthLargest.java ├── Self-Check 7.7: arrayBugs.java ├── Exercise 7.12: priceIsRight.java ├── Exercise 7.8: median.java ├── Self-Check 7.36: jaggedArray.java ├── Self-Check 7.12: traversal.java ├── Self-Check 7.20: ReferenceMystery2.java ├── Self-Check 7.35: arrayMystery2d.java ├── Self-Check 7.19: ReferenceMystery1.java ├── Exercise 7.5: mode.java ├── Exercise 7.2: range.java ├── Exercise 7.6: stdev.java ├── Self-Check 7.21: swapPairs.java └── Exercise 7.11: isUnique.java ├── Chapter 4- Conditional Execution ├── Self-Check 4.3: ifStatementSyntax.java ├── Exercise 4.13: average.java ├── Self-Check 4.10: javaIsAwesome.java ├── Self-Check 4.9: favoriteColor.java ├── Exercise 4.17: stutter.java ├── Self-Check 4.2: logicExpressions1.java ├── Exercise 4.5: pow.java ├── Self-Check 4.15: sumTo.java ├── Self-Check 4.22: countE.java ├── Self-Check 4.6: ifElseMystery2.java ├── Exercise 4.2: repl.java ├── Self-Check 4.7: evenOdd.java ├── Self-Check 4.5: ifElseMystery1.java ├── Self-Check 4.21: capitalLetter.java ├── Exercise 4.1: fractionSum.java ├── Self-Check 4.23: lastFirst.java ├── Exercise 4.14: pow2.java ├── Self-Check 4.11: contribution.java ├── 4.20: numUnique.java ├── Self-Check 4.19: gpaMessage.java ├── Exercise 4.4: daysInMonth.java ├── Self-Check 4.16: countFactors.java ├── Self-Check 4.29: printNumOdd.java ├── Self-Check 4.17: cumulativeProduct.java ├── Self-Check 4.20: charMystery.java ├── Exercise 4.18: wordCount.java ├── Self-Check 4.18: doubleSumError.java ├── Self-Check 4.4: Oops4-errors.java ├── Self-Check 4.8: ScannerLogicError.java ├── Self-Check 4.24: secondHalfLetters.java ├── Exercise 4.7: xo.java ├── Self-Check 4.27: medianOf3.java ├── Self-Check 4.26: getGradePreconditions.java ├── Self-Check 4.12: spending.java ├── Exercise 4.6: printRange.java ├── Exercise 4.9: evenSumMax.java ├── Exercise 4.21: perfectNumbers.java ├── Exercise 4.10: printGPA.java ├── Self-Check 4.13: colors.java ├── Exercise 4.12: printTriangleType.java ├── Exercise 4.8: smallestLargest.java ├── Exercise 4.15: getGrade.java ├── Exercise 4.3: season.java ├── Self-Check 4.28: quadraticPreconditions.java ├── Exercise 4.19: quadrant.java ├── Exercise 4.16: printPalindrome.java ├── Self-Check 4.25: printTriangleTypePreconditions.java └── Self-Check 4.1: logicalTests.java ├── Chapter 3- Parameters and Objects ├── Self-Check 3.11: termForPrintln.java ├── Exercise 3.10: area .java ├── Exercise 3.6: largerAbsVal.java ├── Self-Check 3.16: min.java ├── Self-Check 3.1: methodHeaderSyntax.java ├── Exercise 3.7: largestAbsVal.java ├── Exercise 3.12: scientific.java ├── Exercise 3.15: sphereVolume.java ├── Self-Check 3.2: MysteryNums.java ├── Exercise 3.18: vertical.java ├── Self-Check 3.24: promptMultiplyBy2.java ├── Self-Check 3.10: printStrings.java ├── Self-Check 3.18: jamesTKirk.java ├── Exercise 3.11: distance .java ├── Exercise 3.14: cylinderSurfaceArea.java ├── Exercise 3.19: printReverse.java ├── Self-Check 3.21: fourScore.java ├── Self-Check 3.4: Odds.java ├── Exercise 3.9: lastDigit .java ├── Self-Check 3.17: countQuarters.java ├── Exercise 3.13: pay.java ├── Exercise 3.1: printNumbers.java ├── Self-Check 3.5: Weird.java ├── Self-Check 3.12: Temperature-errors.java ├── Self-Check 3.26: RobertPaulson.java ├── Self-Check 3.23: scannerTokensDouble.java ├── Self-Check 3.25: SumNumbers.java ├── Exercise 3.16: triangleArea.java ├── Self-Check 3.19: stringExpressions.java ├── Self-Check 3.13: mathExpressions.java ├── Exercise 3.21: processName.java ├── Self-Check 3.3: Oops3-errors.java ├── Self-Check 3.20: stringExpressions2.java ├── Exercise 3.17: padString.java ├── Exercise 3.2: printPowersOf2 .java ├── Exercise 3.8: quadratic.java ├── Self-Check 3.9: parameterMysterySoda.java ├── Self-Check 3.7: parameterMysteryWho.java ├── Exercise 3.3: printPowersOfN.java ├── Exercise 3.20: inputBirthday.java ├── Self-Check 3.6: parameterMysteryNumbers.java ├── Self-Check 3.14: parameterMysteryReturn.java ├── Exercise 3.5: printGrid.java ├── Self-Check 3.8: parameterMysteryTouch.java ├── Exercise 3.4: printSquare.java └── Self-Check 3.15: mathExpressions2.java ├── Supplement 3G- Graphics ├── Self-Check 3G.1: drawRectangleSyntax.java ├── Self-Check 3G.2: drawLineErrors.java ├── Self-Check 3G.4: drawLineRectErrors.java ├── Self-Check 3G.3: fillRectErrors.java ├── Exercise 3G.12: Triangle.java ├── Exercise 3G.11a: Stairs2.java ├── Exercise 3G.11b: Stairs3.java ├── Exercise 3G.11c: Stairs4.java ├── Exercise 3G.10: Stairs.java ├── Exercise 3G.9: Squares3.java ├── Exercise 3G.5: ShowDesign.java ├── Exercise 3G.4: Face2.java ├── Exercise 3G.8: Squares2.java ├── Exercise 3G.6: ShowDesign2.java ├── Exercise 3G.13: Football.java ├── Exercise 3G.1: MickeyBox.java ├── Exercise 3G.7: Squares.java ├── Exercise 3G.3: Face.java └── Exercise 3G.2: MickeyBox2.java └── Chapter 12- Recursion ├── Self-Check 12.13: mystery4.java ├── Self-Check 12.4: mystery2.java ├── Self-Check 12.15: mystery6.java ├── Self-Check 12.3: mystery1.java ├── Self-Check 12.6: mysteryXY.java ├── Self-Check 12.14: mystery5.java ├── Self-Check 12.5: mystery3.java ├── Exercise 12.2: writeNums.java └── Exercise 12.1: starString.java /README.md: -------------------------------------------------------------------------------- 1 | # Practice-It 2 | Solving Java programming challenges from the University of Washington's introductory Java courses. 3 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.2: evaluatingExpressions.java: -------------------------------------------------------------------------------- 1 | /*What is the result of the following expression? 2 | 3 | 1 + 2 * 3 + 7 * 2 % 5 4 | */ 5 | 6 | 11 7 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.12: valueOfX.java: -------------------------------------------------------------------------------- 1 | 2 | /*What is the value of variable x after the following code executes? 3 | 4 | 5 | int x = 3; 6 | x = x + 2; 7 | x = x + x;*/ 8 | 9 | 10 10 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.15: printlnSlashes.java: -------------------------------------------------------------------------------- 1 | /*Write a println statement that produces the following output: 2 | 3 | / \ // \\ /// \\\ 4 | 5 | */ 6 | System.out.println("/ \\ // \\\\ /// \\\\\\"); 7 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.9: declareArray.java: -------------------------------------------------------------------------------- 1 | /*Write a piece of code that declares an array variable named data with the elements 7, -1, 13, 24, and 6. 2 | Use only one statement to initialize the array.*/ 3 | int[] data = {7, -1, 13, 24, 6}; 4 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.2: binary1.java: -------------------------------------------------------------------------------- 1 | /*Convert each of the following decimal numbers into its equivalent binary number: 2 | 6 3 | 44 4 | 72 5 | 131 6 | */ 7 | 6 ---> 110 8 | 44 ---> 101100 9 | 72 ---> 1001000 10 | 131 ---> 10000011 11 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.3: binary2.java: -------------------------------------------------------------------------------- 1 | /*What is the decimal equivalent of each of the following binary numbers? 2 | 100 3 | 1011 4 | 101010 5 | 1001110 6 | */ 7 | 100 ---> 4 8 | 1011 ---> 11 9 | 101010 ---> 42 10 | 1001110 ---> 78 11 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.3: ifStatementSyntax.java: -------------------------------------------------------------------------------- 1 | /*Which of the following if statement headers uses the correct syntax? 2 | a. if (x => y) { 3 | b. if (x == y) { 4 | c. if [x == 10] { 5 | d. if (x equals 42) { 6 | e. if x = 10 then { 7 | */ 8 | b. if (x == y) { 9 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.1: legalIntLiterals.java: -------------------------------------------------------------------------------- 1 | /*Which of the following are legal int literals? 2 | a. -6875309 3 | b. 22 4 | c. 10.0 5 | d. 2.3 6 | e. -1 7 | f. 1.5 8 | g. 5. 9 | h. '7' 10 | */ 11 | a. -6875309 12 | b. 22 13 | e. -1 14 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.13: average.java: -------------------------------------------------------------------------------- 1 | /*Write a method called average that takes two integers as parameters and returns the average of the two integers.*/ 2 | public static double average(int a, int b) { 3 |     double average = (double) (a + b) / 2; 4 |     return average; 5 | } 6 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.3: dataArray.java: -------------------------------------------------------------------------------- 1 | /*Write code that creates an array of integers named data of size 5 with the following contents: 2 | 3 | [27, 51, 33, -1, 101] 4 | */ 5 | int[] data = new int[5]; 6 | data[0] = 27; 7 | data[1] = 51; 8 | data[2] = 33; 9 | data[3] = -1; 10 | data[4] = 101; 11 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.23: completeLoop.java: -------------------------------------------------------------------------------- 1 | /*Complete the following for loop to produce the following output: 2 | 3 | -4 4 | 14 5 | 32 6 | 50 7 | 68 8 | 86 9 | */ 10 | int a = -22; 11 | for (int i = 1; i <= 6; i++) { 12 |     a+=18; 13 |     System.out.println(a); 14 | } 15 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.5: starTriangle.java: -------------------------------------------------------------------------------- 1 | /*Write for loops to produce the following output: 2 | 3 | * 4 | ** 5 | *** 6 | **** 7 | ***** 8 | */ 9 | for(int i = 5; i >= 1; i--) { 10 | for(int j = i; j <= 5; j++) { 11 | System.out.print("*"); 12 | } 13 | System.out.println(); 14 | } 15 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.4: starSquare.java: -------------------------------------------------------------------------------- 1 | /*Write for loops to produce the following output: 2 | 3 | ***** 4 | ***** 5 | ***** 6 | ***** 7 | 8 | */ 9 | for(int i = 1; i <= 4; i++) { 10 | for(int j = 1; j <= 5; j++) { 11 | System.out.print("*"); 12 | } 13 | System.out.println(""); 14 | } 15 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.7: spacedNumbers.java: -------------------------------------------------------------------------------- 1 | /*Write nested for loops to produce the following output: 2 | 3 | 1 4 | 2 5 | 3 6 | 4 7 | 5 8 | */ 9 | for(int i = 1; i <= 5; i++) { 10 | for(int j = i; j <= 4; j++) { 11 | System.out.print(" "); 12 | } 13 | System.out.println(i); 14 | } 15 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.11: termForPrintln.java: -------------------------------------------------------------------------------- 1 | /* 2 | The System.out.println command works on many different types of values, including ints and doubles. 3 | What is the term for such a method? 4 | a overload 5 | b overwrite 6 | c override 7 | d overrate 8 | e parameter 9 | */ 10 | a overload 11 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.34: copyColumn.java: -------------------------------------------------------------------------------- 1 | /*Assume that a two-dimensional rectangular array of integers called matrix has been declared with six rows and eight columns. 2 | Write a for loop to copy the contents of the second column into the fifth column.*/ 3 | for(int i = 0; i < 6; i++) { 4 | matrix[i][4] = matrix[i][1]; 5 | } 6 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.4: oddsArray.java: -------------------------------------------------------------------------------- 1 | /*Write code that creates an array named odds and stores all odd numbers between -6 and 38 into it using a for loop. 2 | Make the array's size exactly large enough to store the numbers.*/ 3 | int[] odds = new int[22]; 4 | for(int i = 0; i < 22; i++) { 5 |         odds[i] = i * 2 - 5; 6 | } 7 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.6: numberTriangle .java: -------------------------------------------------------------------------------- 1 | /*Write for loops to produce the following output: 2 | 3 | 1 4 | 22 5 | 333 6 | 4444 7 | 55555 8 | 666666 9 | 7777777 10 | */ 11 | for(int i = 1; i <= 7; i++) { 12 | for(int j = i; j >= 1; j--) { 13 | System.out.print(i); 14 | } 15 | System.out.println(); 16 | } 17 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.14: firstSecond.java: -------------------------------------------------------------------------------- 1 | /*What are the values of first and second at the end of the following code? 2 | 3 | 4 | int first = 8; 5 | int second = 19; 6 | first = first + second; 7 | second = first - second; 8 | first = first - second;*/ 9 | 10 | first ------> 19 11 | second ------> 8 12 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.10: Shaq.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following statements? 2 | 3 | System.out.println("Shaq is 7'1"); 4 | System.out.println("The string \"\" is an empty message."); 5 | System.out.println("\\'\"\""); 6 | */ 7 | Shaq is 7'1 8 | The string "" is an empty message. 9 | \'"" 10 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.27: howManyLines .java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following loop? 2 | 3 | 4 | for (int i = 1; i <= 3; i++) 5 | System.out.println("How many lines"); 6 | System.out.println("are printed?"); 7 | */ 8 | 9 | How many lines 10 | How many lines 11 | How many lines 12 | are printed? 13 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.32: rectangularArray.java: -------------------------------------------------------------------------------- 1 | /*Assume that a two-dimensional rectangular array of integers called data has been declared with four rows and seven columns. 2 | Write a for loop to initialize the third row of data to store the numbers 1 through 7.*/ 3 | for (int c = 1; c <= data[2].length; c++) { 4 |     data[2][c - 1] = c; 5 | } 6 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.8: confounding.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following statements? 2 | 3 | System.out.println("\"Quotes\""); 4 | System.out.println("Slashes \\//"); 5 | System.out.println("How '\"confounding' \"\\\" it is!"); 6 | */ 7 | "Quotes" 8 | Slashes \// 9 | How '"confounding' "\" it is! 10 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.16: valuesOfIJK.java: -------------------------------------------------------------------------------- 1 | /*What are the values of i, j, and k after the following code statements? 2 | 3 | 4 | int i = 2; 5 | int j = 3; 6 | int k = 4; 7 | int x = i + j + k; 8 | i = x - i - j; 9 | j = x - j - k; 10 | k = x - i - k;*/ 11 | 12 | i -------> 4 13 | j -------> 2 14 | k -------> 1 15 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.1: arrayDeclarationSyntax.java: -------------------------------------------------------------------------------- 1 | /* 2 | Which of the following choices is the correct syntax for declaring/initializing an array of ten integers? 3 | a. int[10] a = new int[10]; 4 | b. int a[10]; 5 | c. int[] a = new int[10]; 6 | d. []int a = [10]int; 7 | e. int a[10] = new int[10]; 8 | */ 9 | int[] a = new int[10]; 10 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.28: blastOff.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following loop? 2 | 3 | 4 | System.out.println("T-minus "); 5 | for (int i = 5; i >= 1; i--) { 6 | System.out.println(i + ", "); 7 | } 8 | System.out.println("Blastoff!"); 9 | */ 10 | T-minus 11 | 5, 12 | 4, 13 | 3, 14 | 2, 15 | 1, 16 | Blastoff! 17 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.21: methodHeaderSyntax.java: -------------------------------------------------------------------------------- 1 | /*Which of the following method headers uses the correct syntax? 2 | a.public static void example() { 3 | b.public void static example() { 4 | c.public static example void[] { 5 | d.public static example() { 6 | e.public void static example{} ( 7 | */ 8 | a.public static void example() { 9 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.13: valuesOfABC.java: -------------------------------------------------------------------------------- 1 | /*What are the values of a, b, and c after the following code statements? (It may help you to write down their values after 2 | each line.) 3 | 4 | 5 | int a = 5; 6 | int b = 10; 7 | int c = b; 8 | a = a + 1; 9 | b = b - 1; 10 | c = c + a;*/ 11 | 12 | a -------> 6 13 | b -------> 9 14 | c -------> 16 15 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.9: lastDigitExpression.java: -------------------------------------------------------------------------------- 1 | /*Suppose you have an int variable called number. What Java expression produces the last digit of the number (the 1s place)? 2 | (Our code checker won't match every possible expression; come up with the simplest expression using division and modulus.)*/ 3 | 4 | the 1s place of number --------> number % 10 5 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.24: oddStuff.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following oddStuff method? 2 | 3 | 4 | public static void oddStuff() { 5 | int number = 4; 6 | for (int count = 1; count <= number; count++) { 7 | System.out.println(number); 8 | number = number / 2; 9 | } 10 | }*/ 11 | 12 | 4 13 | 2 14 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.4: cookieRecipe.java: -------------------------------------------------------------------------------- 1 | /*In your own words, describe an algorithm for baking cookies. Assume that you have a large number of hungry friends, 2 | so you'll want to produce several batches of cookies! 3 | 4 | (Since there are so many correct answers, Practice-It will accept any solution of sufficient length.) 5 | 6 | recipe 7 | */ 8 | cookieRecipe(); 9 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.8: spacesAndNumbers.java: -------------------------------------------------------------------------------- 1 | /*Write nested for loops to produce the following output: 2 | 3 | 1 4 | 22 5 | 333 6 | 4444 7 | 55555 8 | /* 9 | 10 | for(int i = 1; i <= 5; i++) { 11 | for(int j = 5 - i; j > 0; j--) 12 | System.out.print(" "); 13 | for(int j = 0; j < i; j++) 14 | System.out.print(i); 15 | System.out.println(); 16 | } 17 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.7: outputSyntax.java: -------------------------------------------------------------------------------- 1 | /*Which of the following is the correct syntax to output a message? 2 | a.System.println("Hello, world!"); 3 | b.System.out.println("Hello, world!"); 4 | c.System.println(Hello, world!); 5 | d.Out.system.println"(Hello, world!)"; 6 | e.System.println.out('Hello, world!'); 7 | */ 8 | b.System.out.println("Hello, world!"); 9 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.25: numberTotal.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following loop? 2 | int total = 25; 3 | for (int number = 1; number <= (total / 2); number++) { 4 | total = total - number; 5 | System.out.println(total + " " + number); 6 | } 7 | */ 8 | 9 | 10 | output: 11 | 24 1 12 | 22 2 13 | 19 3 14 | 15 4 15 | 10 5 16 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.6: declareRealNumberSyntax.java: -------------------------------------------------------------------------------- 1 | /*Which of the following choices is the correct syntax for declaring a real number variable named 'grade' and 2 | initializing its value to 4.0? 3 | 4 | a. double grade = 4.0; 5 | b. int grade : 4.0; 6 | c. grade = double 4.0; 7 | d. 4.0 = grade; 8 | e. grade = 4; 9 | */ 10 | a. double grade = 4.0; 11 | 12 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.10: area .java: -------------------------------------------------------------------------------- 1 | /*Write a method named area that accepts the radius of a circle as a parameter and returns the area of a circle with that 2 | radius. For example, the call area(2.0) should return 12.566370614359172. You may assume that the radius is non-negative.*/ 3 | 4 | public static double area(double number) { 5 |     return Math.PI * number * number; 6 | } 7 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.6: largerAbsVal.java: -------------------------------------------------------------------------------- 1 | /*Write a method called largerAbsVal that takes two integers as parameters and returns the larger of the two absolute values. 2 | A call of largerAbsVal(11, 2) would return 11, and a call of largerAbsVal(4, -5) would return 5.*/ 3 | 4 | public int largerAbsVal(int num1, int num2) { 5 |     return Math.max(Math.abs(num1), Math.abs(num2)); 6 | } 7 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.14: arrayCodeTracing2.java: -------------------------------------------------------------------------------- 1 | /*Fill in the array with the values that would be stored after the code executes: 2 | 3 | 4 | int[] list = {2, 18, 6, -4, 5, 1}; 5 | for (int i = 0; i < list.length; i++) { 6 | list[i] = list[i] + (list[i] / list[0]); 7 | }*/ 8 | 9 | list[0] = 3 10 | list[1] = 24 11 | list[2] = 8 12 | list[3] = -5 13 | list[4] = 6 14 | list[5] = 1 15 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Self-Check 3G.1: drawRectangleSyntax.java: -------------------------------------------------------------------------------- 1 | /*Which of the following is the correct syntax to draw a rectangle? 2 | a. Graphics.drawRect(10, 20, 50, 30); 3 | b. g.drawRect(x = 10, y = 20, width = 50, height = 30); 4 | c. g.drawRect(10, 20, 50, 30); 5 | d. g.draw.rectangle(10, 20, 50, 30); 6 | e. Graphics g.drawRect(10, 20, 50, 30);*/ 7 | 8 | c. g.drawRect(10, 20, 50, 30); 9 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.16a: countStrings.java: -------------------------------------------------------------------------------- 1 | /*Write a method countStrings that takes an array of Strings and a target String and returns the number of occurences target appears 2 | in the array.*/ 3 | 4 | public static int countStrings(String[] string, String s) { 5 | int i = 0; 6 | for(String x : string) { 7 | if(x.equals(s)) { 8 | i++; 9 | } 10 | } 11 | return i; 12 | } 13 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.16: min.java: -------------------------------------------------------------------------------- 1 | /*Write a method called min that takes three integers as parameters and returns the smallest of the three values, such that 2 | a call of min(3, -2, 7) would return -2, and a call of min(19, 27, 6) would return 6. Use Math.min to write your solution.*/ 3 | 4 | public static int min(int a, int b, int c) { 5 |     return Math.min(a, Math.min(b, c)); 6 | } 7 | 8 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.2: numbersElements.java: -------------------------------------------------------------------------------- 1 | /* 2 | -What expression should be used to access the first element of an array of integers called numbers? 3 | -What expression should be used to access the last element of numbers, assuming it contains 10 elements? 4 | -What expression can be used to access its last element, regardless of its length?*/ 5 | numbers[0] 6 | numbers[9] 7 | numbers[numbers.length-1] 8 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Self-Check 12.13: mystery4.java: -------------------------------------------------------------------------------- 1 | /*For each call to the following method, indicate what value is returned: 2 | 3 | public int mystery4(int x, int y) { 4 | if (x < y) { 5 | return x; 6 | } else { 7 | return mystery4(x - y, y); 8 | } 9 | }*/ 10 | 11 | mystery4(6, 13) 6 12 | mystery4(14, 10) 4 13 | mystery4(37, 10) 7 14 | mystery4(8, 2) 0 15 | mystery4(50, 7) 1 16 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.26: fingerTrap.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following loop? 2 | 3 | 4 | System.out.println("+----+"); 5 | for (int i = 1; i <= 3; i++) { 6 | System.out.println("\\ /"); 7 | System.out.println("/ \\"); 8 | } 9 | System.out.println("+----+"); 10 | */ 11 | 12 | +----+ 13 | \ / 14 | / \ 15 | \ / 16 | / \ 17 | \ / 18 | / \ 19 | +----+ 20 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.13: Sally.java: -------------------------------------------------------------------------------- 1 | /*What series of println statements would produce the following output? 2 | 3 | "Several slashes are sometimes seen," 4 | said Sally. "I've said so." See? 5 | \ / \\ // \\\ /// 6 | */ 7 | System.out.println("\"Several slashes are sometimes seen,\""); 8 | System.out.println("said Sally. \"I've said so.\" See?"); 9 | System.out.println("\\ / \\\\ // \\\\\\ ///"); 10 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.17: maxMin.java: -------------------------------------------------------------------------------- 1 | /*What is the output from the following code? 2 | 3 | 4 | int max; 5 | int min = 10; 6 | max = 17 - 4 / 10; 7 | max = max + 6; 8 | min = max - min; 9 | System.out.println(max * 2); 10 | System.out.println(max + min); 11 | System.out.println(max); 12 | System.out.println(min);*/ 13 | 14 | 15 | output: 16 | 46 17 | 36 18 | 23 19 | 13 20 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.10: javaIsAwesome.java: -------------------------------------------------------------------------------- 1 | /*The following code is poorly structured. It contains redundant statements that unnecessarily occur multiple times. Factor out 2 | redundant code from the following example by moving it out of the if/else statement, while preserving the same behavior and output.*/ 3 | 4 | if (x < 30) { 5 |     x++; 6 | } 7 |     a = 2; 8 |     System.out.println("Java is awesome! " + x); 9 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.32: starExclamation2.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following sequence of loops? 2 | 3 | 4 | for (int i = 1; i <= 2; i++) { 5 | for (int j = 1; j <= 3; j++) { 6 | for (int k = 1; k <= 4; k++) { 7 | System.out.print("*"); 8 | } 9 | } 10 | System.out.print("!"); 11 | System.out.println(); 12 | }*/ 13 | ************! 14 | ************! 15 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.1: methodHeaderSyntax.java: -------------------------------------------------------------------------------- 1 | /*Which of the following is the correct syntax for a method header with parameters? 2 | a public static (int x, int y) example() { 3 | b public static void example(x, y) { 4 | c public static void example(x: int, y: int) { 5 | d public static void example(int x, int y) { 6 | e public static void example(int x,y) { 7 | */ 8 | d public static void example(int x, int y) { 9 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.6: legalIdentifiers.java: -------------------------------------------------------------------------------- 1 | /*Which of the following can be used in a Java program as identifiers? Check all of the identifiers that are legal. 2 | ABC 3 | for 4 | B4 5 | _average 6 | 42isThesolution 7 | sum_of_data 8 | println 9 | first-name 10 | AnnualSalary 11 | "hello" 12 | */ 13 | ABC 14 | B4 15 | _average 16 | sum_of_data 17 | println 18 | AnnualSalary 19 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.31: starExclamation1.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following sequence of loops? 2 | 3 | 4 | for (int i = 1; i <= 2; i++) { 5 | for (int j = 1; j <= 3; j++) { 6 | for (int k = 1; k <= 4; k++) { 7 | System.out.print("*"); 8 | } 9 | System.out.print("!"); 10 | } 11 | System.out.println(); 12 | }*/ 13 | ****!****!****! 14 | ****!****!****! 15 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.9: favoriteColor.java: -------------------------------------------------------------------------------- 1 | /*The following code contains a bug. Examine the code and figure out the case(s) in which the code would behave incorrectly. 2 | Then correct the bug in the code.*/ 3 | 4 | Scanner console = new Scanner(System.in); 5 | System.out.print("What is your favorite color? "); 6 | String name = console.next(); 7 | if (name.equals("blue")) { 8 |     System.out.println("Mine, too!"); 9 | } 10 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.5: numbersArray.java: -------------------------------------------------------------------------------- 1 | /*What elements does the array numbers contain after the following code is executed? (Write the elements in the format: 2 | {0, 1, 2, ...} ) 3 | 4 | 5 | int[] numbers = new int[8]; 6 | numbers[1] = 4; 7 | numbers[4] = 99; 8 | numbers[7] = 2; 9 | ​ 10 | int x = numbers[1]; 11 | numbers[x] = 44; 12 | numbers[numbers[7]] = 11; // uses numbers[7] as index*/ 13 | 14 | {0, 4, 11, 0, 44, 0, 0, 2} 15 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.17: stutter.java: -------------------------------------------------------------------------------- 1 | /*Write a method called stutter that accepts a parameter and returns the String with its characters returns repeated twice. 2 | For example, stutter("Hello!") returns "HHeelllloo!!"*/ 3 | public static String stutter(String string) { 4 | String s = ""; 5 | for(int i = 0; i < string.length(); i++) { 6 | s = s + string.charAt(i) + string.charAt(i); 7 | 8 | } 9 | return s; 10 | } 11 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.33: fiveByTenArray.java: -------------------------------------------------------------------------------- 1 | /*Write a piece of code that constructs a two-dimensional array of integers named table with 5 rows and 10 columns. Fill the array 2 | with a multiplication table, so that array element [i][j] contains the value i * j. Use nested for loops to build the array.*/ 3 | int[][] table = new int[5][10]; 4 | for (int i = 0; i < 5; i++) { 5 | for (int j = 0; j < 10; j++) { 6 | table[i][j] = i * j; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.12: nestedNumbers.java: -------------------------------------------------------------------------------- 1 | /*Write nested for loops that produce the following output: 2 | 3 | 4 | 000111222333444555666777888999 5 | 000111222333444555666777888999 6 | 000111222333444555666777888999 7 | 8 | */ 9 | 10 | for(int i = 1; i <= 3; i++) { 11 |     for(int j = 0; j <= 9; j++) { 12 |         for(int k = 1; k <= 3; k++) 13 |             System.out.print(j); 14 |     } 15 |     System.out.println(); 16 | } 17 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.2: loopSquares .java: -------------------------------------------------------------------------------- 1 | /*Write a for loop that produces the following output: 2 | 3 | 1 4 9 16 25 36 49 64 81 100 4 | For added challenge, try to modify your code so that it does not need to use the * multiplication operator. 5 | (It can be done! Hint: Look at the differences between adjacent numbers.)*/ 6 | 7 | int a = 1; 8 | for(int i = 1; i <= 100; i+=a) { 9 | a += 2; 10 | System.out.print(i + " "); 11 | } 12 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.33: starExclamation3.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following sequence of loops? 2 | 3 | 4 | for (int i = 1; i <= 2; i++) { 5 | for (int j = 1; j <= 3; j++) { 6 | for (int k = 1; k <= 4; k++) { 7 | System.out.print("*"); 8 | System.out.print("!"); 9 | } 10 | } 11 | System.out.println(); 12 | }*/ 13 | *!*!*!*!*!*!*!*!*!*!*!*! 14 | *!*!*!*!*!*!*!*!*!*!*!*! 15 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.7: largestAbsVal.java: -------------------------------------------------------------------------------- 1 | /*Write a method largestAbsVal that accepts three integers as parameters and returns the largest of their three absolute values. 2 | For example, a call of largestAbsVal(7, -2, -11) would return 11, and a call of largestAbsVal(-4, 5, 2) would return 5.*/ 3 | 4 | public static int largestAbsVal(int num1, int num2, int num3) { 5 |     return Math.max(Math.abs(num1), Math.max(Math.abs(num2), Math.abs(num3))); 6 | } 7 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.9: Archie.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following statements? (Treat tabs as aligning to every multiple of eight spaces.) 2 | 3 | System.out.println("name\tage\theight"); 4 | System.out.println("Archie\t17\t5'9\""); 5 | System.out.println("Betty\t17\t5'6\""); 6 | System.out.println("Jughead\t16\t6'"); 7 | */ 8 | name age height 9 | Archie 17 5'9" 10 | Betty 17 5'6" 11 | Jughead 16 6' 12 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.6: fillDataArray.java: -------------------------------------------------------------------------------- 1 | /*Fill in the array with the values that would be stored after the code executes: 2 | 3 | 4 | int[] data = new int[8]; 5 | data[0] = 3; 6 | data[7] = -18; 7 | data[4] = 5; 8 | data[1] = data[0]; 9 | ​ 10 | int x = data[4]; 11 | data[4] = 6; 12 | data[x] = data[0] * data[1]; 13 | */ 14 | 15 | data[0] = 3 16 | data[1] = 3 17 | data[2] = 0 18 | data[3] = 0 19 | data[4] = 6 20 | data[5] = 9 21 | data[6] = 0 22 | data[7] = -18 23 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Self-Check 3G.2: drawLineErrors.java: -------------------------------------------------------------------------------- 1 | /*There are three mistakes in the following code, which attempts to draw a line from coordinates (50, 86) to (20, 35): 2 | 3 | 4 | DrawingPanel panel = new DrawingPanel(200, 200); 5 | panel.drawLine(50, 20, 86, 35); 6 | Find the mistakes and correct the code. Type the correct code below.*/ 7 | 8 | DrawingPanel panel = new DrawingPanel(200, 200); 9 | Graphics g = panel.getGraphics(); 10 | g.drawLine(50, 86, 20, 35); 11 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.2: logicExpressions1.java: -------------------------------------------------------------------------------- 1 | /*Given the following variable declarations: 2 | 3 | int x = 4; 4 | int y = -3; 5 | int z = 4; 6 | What are the results of the following relational expressions?*/ 7 | 8 | x == 4 true 9 | x == y false 10 | x == z true 11 | y == z false 12 | x + y > 0 true 13 | x - z != 0 false 14 | y * y <= z false 15 | y / y == 1 true 16 | x * (y + 2) > y - (y + z) * 2 true 17 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.11: downwardSpiral.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following statements? (Treat tabs as aligning to every multiple of eight spaces.) 2 | 3 | System.out.println("\ta\tb\tc"); 4 | System.out.println("\\\\"); 5 | System.out.println("'"); 6 | System.out.println("\"\"\""); 7 | System.out.println("C:\nin\the downward spiral"); 8 | */ 9 | a b c 10 | \\ 11 | ' 12 | """ 13 | C: 14 | in he downward spiral 15 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.29: multiplication.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following sequence of loops? 2 | 3 | 4 | for (int i = 1; i <= 5; i++) { 5 | for (int j = 1; j <= 10; j++) { 6 | System.out.print((i * j) + " "); 7 | } 8 | System.out.println(); 9 | } 10 | */ 11 | 1 2 3 4 5 6 7 8 9 10 12 | 2 4 6 8 10 12 14 16 18 20 13 | 3 6 9 12 15 18 21 24 27 30 14 | 4 8 12 16 20 24 28 32 36 40 15 | 5 10 15 20 25 30 35 40 45 50 16 | 17 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Self-Check 12.4: mystery2.java: -------------------------------------------------------------------------------- 1 | /*For each call to the following method, indicate what console output is produced: 2 | 3 | public void mystery2(int n) { 4 | if (n > 100) { 5 | System.out.print(n); 6 | } else { 7 | mystery2(2 * n); 8 | System.out.print(", " + n); 9 | } 10 | }*/ 11 | 12 | mystery2(113); 113 13 | mystery2(70); 140, 70 14 | mystery2(42); 168, 84, 42 15 | mystery2(30); 120, 60, 30 16 | mystery2(10); 160, 80, 40, 20, 10 17 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.18: timesOperator.java: -------------------------------------------------------------------------------- 1 | /*Suppose a real number variable x is defined. Write a single Java statement that stores as a variable y the result of 2 | the computation below, modifying the expression to use the * operator exactly four times when computing 3 | an equivalent value (hint: how could you factor out x here?). 4 | 5 | y = 12.3x4 - 9.1x3 + 19.3x2 - 4.6x + 34.2 6 | */ 7 | 8 | double y = x * (x * (19.3 + x * (12.3 * x - 9.1)) - 4.6) + 34.2; 9 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.8: arrayDeclarationSyntax2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Which of the following choices is the correct syntax for quickly declaring/initializing an array of six integers to store a 3 | particular list of values? 4 | a. int[] a = {17, -3, 42, 5, 9, 28}; 5 | b. int a {17, -3, 42, 5, 9, 28}; 6 | c. int[6] a = {17, -3, 42, 5, 9, 28}; 7 | d. int[] a = new {17, -3, 42, 5, 9, 28} [6]; 8 | e. int[] a = new int[6] {17, -3, 42, 5, 9, 28};*/ 9 | int[] a = {17, -3, 42, 5, 9, 28}; 10 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.12: scientific.java: -------------------------------------------------------------------------------- 1 | /*Write a method called scientific that accepts two real numbers as parameters for a base and an exponent and computes the base 2 | times 10 to the exponent, as seen in scientific notation. 3 | For example, the call of scientific(6.23, 5.0) would return 623000.0 and the call of scientific(1.9, -2.0) would return 0.019.*/ 4 | 5 | public static double scientific(double base, double exponent) { 6 |     return base * Math.pow(10, exponent); 7 | } 8 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.15: sphereVolume.java: -------------------------------------------------------------------------------- 1 | /*Write a method called sphereVolume that accepts a radius (a real number) as a parameter and returns the volume of a sphere 2 | with that radius. For example, the call sphereVolume(2.0) should return 33.510321638291124. The formula for the volume of a 3 | sphere with radius r is the following: 4 | 5 | volume = 4/3 π r3 6 | */ 7 | 8 | public static double sphereVolume(double r) { 9 |     return 4 * Math.PI * r * r * r / 3; 10 | } 11 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.2: MysteryNums.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following program? 2 | 3 | 4 | public class MysteryNums { 5 | public static void main(String[] args) { 6 | int x = 15; 7 | sentence(x, 42); 8 | ​ 9 | int y = x - 5; 10 | sentence(y, x + y); 11 | } 12 | ​ 13 | public static void sentence(int num1, int num2) { 14 | System.out.println(num1 + " " + num2); 15 | } 16 | }*/ 17 | 18 | 15 42 19 | 10 25 20 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Self-Check 12.15: mystery6.java: -------------------------------------------------------------------------------- 1 | /*For each call to the following method, indicate what value is returned: 2 | 3 | public static int mystery6(int n, int k) { 4 | if (k == 0 || k == n) { 5 | return 1; 6 | } else if (k > n) { 7 | return 0; 8 | } else { 9 | return mystery6(n - 1, k - 1) + mystery6(n - 1, k); 10 | } 11 | }*/ 12 | 13 | mystery6(7, 1) 7 14 | mystery6(4, 2) 6 15 | mystery6(4, 3) 4 16 | mystery6(5, 3) 10 17 | mystery6(5, 4) 5 18 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.18: vertical.java: -------------------------------------------------------------------------------- 1 | /*Write a method called vertical that accepts a String as its parameter and prints each letter of the string on separate lines. 2 | For example, a call of vertical("hey now") should produce the following output: 3 | 4 | h 5 | e 6 | y 7 | 8 | n 9 | o 10 | w 11 | 12 | */ 13 | public static void vertical(String string) { 14 |     for(int i = 0; i < string.length(); i++) { 15 |         System.out.println(string.charAt(i)); 16 |     } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.24: promptMultiplyBy2.java: -------------------------------------------------------------------------------- 1 | /*Write code to read an integer from the user, then print that number multiplied by 2. You may assume that the user types a valid integer. A sample run of the code would produce the following: 2 | 3 | Type an integer: 4 4 | 4 times 2 = 8 5 | */ 6 | 7 | Scanner input = new Scanner(System.in); 8 | System.out.print("Type an integer: "); 9 | int number = input.nextInt(); 10 | System.out.println(number + " times 2 = " + number * 2); 11 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.5: pow.java: -------------------------------------------------------------------------------- 1 | /*Write a method named pow that accepts a base and an exponent as parameters and returns the base raised to the given power. 2 | For example, the call pow(3, 4) returns 3 * 3 * 3 * 3 or 81. Do not use Math.pow in your solution. Assume that the base and 3 | exponent are non-negative.*/ 4 | 5 | public static int pow(int base, int ex) { 6 | int s = 1; 7 | for(int i = 1; i <= ex; i++) { 8 | s *= base; 9 | } 10 |         return s; 11 | } 12 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.22: arrayCodeTracing3.java: -------------------------------------------------------------------------------- 1 | /*What are the values of the elements in the array numbers after the following code is executed? 2 | 3 | 4 | int[] numbers = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 5 | for (int i = 0; i < 9; i++) { 6 | numbers[i] = numbers[i + 1]; 7 | }*/ 8 | 9 | numbers[0] 20 10 | numbers[1] 30 11 | numbers[2] 40 12 | numbers[3] 50 13 | numbers[4] 60 14 | numbers[5] 70 15 | numbers[6] 80 16 | numbers[7] 90 17 | numbers[8] 100 18 | numbers[9] 100 19 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.23: arrayCodeTracing4.java: -------------------------------------------------------------------------------- 1 | /*What are the values of the elements in the array numbers after the following code is executed? 2 | 3 | 4 | int[] numbers = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 5 | for (int i = 1; i < 10; i++) { 6 | numbers[i] = numbers[i - 1]; 7 | }*/ 8 | 9 | numbers[0] 10 10 | numbers[1] 10 11 | numbers[2] 10 12 | numbers[3] 10 13 | numbers[4] 10 14 | numbers[5] 10 15 | numbers[6] 10 16 | numbers[7] 10 17 | numbers[8] 10 18 | numbers[9] 10 19 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.10: printStrings.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printStrings that accepts a String and a number of repetitions as parameters and prints that String 2 | the given number of times. For example, the call: 3 | 4 | 5 | printStrings("abc", 5); 6 | will print the following output: 7 | 8 | abcabcabcabcabc 9 | */ 10 | 11 | public static void printStrings(String string, int n) { 12 |     for(int i = 1; i <= n; i++) { 13 |         System.out.print(string); 14 |     } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.15: printBackwards.java: -------------------------------------------------------------------------------- 1 | /*Write a method printBackwards that prints an array of integers in reverse order, in the following format. 2 | 3 | For the array {1, -3, 4, 7, 2}: 4 | 5 | element [4] is 2 6 | element [3] is 7 7 | element [2] is 4 8 | element [1] is -3 9 | element [0] is 1 10 | */ 11 | public static void printBackwards(int[] data) { 12 |     for(int i = data.length - 1; i >= 0; i--) { 13 |         System.out.println("element [" + i + "] is " + data[i]); 14 |     } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.15: sumTo.java: -------------------------------------------------------------------------------- 1 | /*What is wrong with the following sumTo method, which attempts to add all numbers from 1 to a given maximum? Correct the code so 2 | that it properly implements this behavior. For example the call of sumTo(5) should return 1+2+3+4+5 = 15. You may assume that the 3 | value passed is at least 1.*/ 4 | 5 | public static int sumTo(int n) { 6 |     int sum = 0; 7 |     for (int i = 1; i <= n; i++) { 8 |         sum += i; 9 |     } 10 |     return sum; 11 | } 12 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.21: Count2.java: -------------------------------------------------------------------------------- 1 | /*Complete the following code, replacing the "FINISH ME" parts with your own code, to produce the following output: 2 | 3 | 2 times 1 = 2 4 | 2 times 2 = 4 5 | 2 times 3 = 6 6 | 2 times 4 = 8 7 | */ 8 | public class Count2 { 9 |     public static void main(String[] args) { 10 |         for (int i = 1; i <= 4; i++) { 11 |             int multi = 2 * i; 12 |             System.out.println(2 + " times " + i + " = " + multi); 13 |         } 14 |     } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.24: arrayMystery1.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method, mystery. 2 | 3 | 4 | public static void mystery(int[] a, int[] b) { 5 | for (int i = 0; i < a.length; i++) { 6 | a[i] += b[b.length - 1 - i]; 7 | } 8 | } 9 | What are the values of the elements in array a1 after the following code executes? 10 | 11 | 12 | int[] a1 = {1, 3, 5, 7, 9}; 13 | int[] a2 = {1, 4, 9, 16, 25}; 14 | mystery(a1, a2); 15 | */ 16 | a1[0] 26 17 | a1[1] 19 18 | a1[2] 14 19 | a1[3] 11 20 | a1[4] 10 21 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.22: countE.java: -------------------------------------------------------------------------------- 1 | /*What is wrong with the following code, which attempts to count the number occurrences of the letter 'e' in a string, case-insensitively? 2 | Determine what is wrong with the code, and submit a corrected version that works properly. Use at least one method call from the Character 3 | class in your solution.*/ 4 | 5 | int count = 0; 6 | for (int i = 0; i < s.length(); i++) { 7 |     if (Character.toLowerCase(s.charAt(i)) == 'e') { 8 |         count++; 9 |     } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.1: Stewie.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named Stewie that prints the following output: 2 | 3 | ////////////////////// 4 | || Victory is mine! || 5 | \\\\\\\\\\\\\\\\\\\\\\ 6 | */ 7 | public class Stewie { 8 |     public static void main(String[] args) { 9 |         System.out.println("//////////////////////"); 10 |         System.out.println("|| Victory is mine! ||"); 11 |         System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"); 12 |     } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Self-Check 12.3: mystery1.java: -------------------------------------------------------------------------------- 1 | /*For each call to the following method, indicate what console output is produced: 2 | 3 | public void mystery1(int n) { 4 | if (n <= 1) { 5 | System.out.print(n); 6 | } else { 7 | mystery1(n / 2); 8 | System.out.print(", " + n); 9 | } 10 | }*/ 11 | 12 | mystery1(1); 1 13 | mystery1(4); 1, 2, 4 14 | mystery1(16); 1, 2, 4, 8, 16 15 | mystery1(30); 1, 3, 7, 15, 30 16 | mystery1(100); 1, 3, 6, 12, 25, 50, 100 17 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.18: jamesTKirk.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following code? 2 | 3 | 4 | String first = "James"; 5 | String last = "Kirk"; 6 | String middle = "T."; 7 | System.out.println(last); 8 | System.out.println("My name is " + first); 9 | System.out.println(first + " " + last); 10 | System.out.println(last + ", " + first + " " + middle); 11 | System.out.println(middle + " is for Tiberius"); 12 | */ 13 | 14 | Kirk 15 | My name is James 16 | James Kirk 17 | Kirk, James T. 18 | T. is for Tiberius 19 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.11: digitExpressions.java: -------------------------------------------------------------------------------- 1 | /*Suppose you have an int variable called number. What Java expression produces the second-to-last digit of the number (the 10s 2 | place)? What expression produces the third-to-last digit of the number (the 100s place)? (Note: Our code checker won't match 3 | every possible expression; please come up with the simplest expression using division and modulus.)*/ 4 | 5 | 6 | 10s place ------------> (number % 100) / 10 7 | 100s place ------------> (number % 1000) / 100 8 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.6: ifElseMystery2.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method. 2 | 3 | 4 | public static void ifElseMystery2(int a, int b) { 5 | if (a * 2 < b) { 6 | a = a * 3; 7 | } 8 | if (b < a) { 9 | b++; 10 | } else { 11 | a--; 12 | } 13 | System.out.println(a + " " + b); 14 | } 15 | For each call below, indicate what output is produced.*/ 16 | 17 | ifElseMystery2(10, 2); 10 3 18 | ifElseMystery2(3, 8); 9 9 19 | ifElseMystery2(4, 4); 3 4 20 | ifElseMystery2(10, 30); 29 30 21 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.15: firstSecond2.java: -------------------------------------------------------------------------------- 1 | /*Rewrite the following code from the previous exercise to be shorter, by declaring the variables together on the same line, and 2 | by using the special assignment operators (e.g., +=, -=, *=, and /=) as appropriate. 3 | 4 | 5 | int first = 8; 6 | int second = 19; 7 | first = first + second; 8 | second = first - second; 9 | first = first - second;*/ 10 | 11 | shortened code: 12 | int first = 8, second = 19; 13 | first += second; 14 | second = first - second; 15 | first -= second; 16 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.7: fitnessVariables.java: -------------------------------------------------------------------------------- 1 | /*Imagine you are writing a personal fitness program that stores the user's age, gender, height (in feet or meters), and 2 | weight (to the nearest pound or kilogram). Declare variables with the appropriate names and types to hold this information. 3 | Write a complete variable declaration statement with the type, the variable name, and a semicolon.*/ 4 | 5 | age -------> int age; 6 | gender -------> String gender; 7 | height -------> double height; 8 | weight -------> int weight; 9 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.19: SecretMessage-errors.java: -------------------------------------------------------------------------------- 1 | /*The following program contains four errors. Correct the errors and submit a working version of the program. 2 | 3 | public class SecretMessage { 4 | public static main(string[] args) { 5 | System.out.println("Speak friend"); 6 | System.out.println("and enter); 7 | }*/ 8 | public class SecretMessage { 9 |     public static void main(String[] args) { 10 |         System.out.println("Speak friend"); 11 |         System.out.println("and enter"); 12 |     } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.8: studentVariables.java: -------------------------------------------------------------------------------- 1 | /*Imagine you are writing a program that stores a student's year (Freshman, Sophomore, Junior, or Senior), the number of 2 | courses the student is taking, and his or her GPA on a 4.0 scale. Declare variables with the appropriate names and types to 3 | hold this information. Write a complete variable declaration statement with the type, the variable name, and a semicolon.*/ 4 | 5 | year -------> String year; 6 | courses taken -------> int courses; 7 | GPA -------> double gpa; 8 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Self-Check 12.6: mysteryXY.java: -------------------------------------------------------------------------------- 1 | /*For each call to the following method, indicate what console output is produced: 2 | 3 | public void mysteryXY(int x, int y) { 4 | if (y == 1) { 5 | System.out.print(x); 6 | } else { 7 | System.out.print(x * y + ", "); 8 | mysteryXY(x, y - 1); 9 | System.out.print(", " + x * y); 10 | } 11 | }*/ 12 | 13 | mysteryXY(4, 1); 4 14 | mysteryXY(4, 2); 8, 4, 8 15 | mysteryXY(8, 2); 16, 8, 16 16 | mysteryXY(4, 3); 12, 8, 4, 8, 12 17 | mysteryXY(3, 4); 12, 9, 6, 3, 6, 9, 12 18 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.11: distance .java: -------------------------------------------------------------------------------- 1 | /*Write a method called distance that accepts four integer coordinates x1, y1, x2, and y2 as parameters and computes the 2 | distance between points (x1, y1) and (x2, y2) on the Cartesian plane. 3 | 4 | For example, the call of distance(1, 0, 4, 4) would return 5.0 and the call of distance(10, 2, 3, 5) would return 7.615773105863909.*/ 5 | 6 | public static double distance(int x1, int y1, int x2, int y2) { 7 |     double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); 8 |     return Math.sqrt(d); 9 | } 10 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.2: repl.java: -------------------------------------------------------------------------------- 1 | /*Write a method named repl that accepts a String and a number of repetitions as parameters and returns the String concatenated 2 | that many times. For example, the call repl("hello", 3) returns "hellohellohello". If the number of repetitions is 0 or less, 3 | an empty string is returned.*/ 4 | 5 | public static String repl(String string, int r) { 6 | if(r <= 0) { 7 | return ""; 8 | } else { 9 | String s = ""; 10 | for(int i = 1; i <= r; i++) 11 | s+=string; 12 | return s; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.7: evenOdd.java: -------------------------------------------------------------------------------- 1 | /*Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise. You may 2 | assume that the user types a valid integer. The input/output should match the following example: 3 | 4 | Type a number: 14 5 | even 6 | 7 | */ 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Type a number: "); 10 | int number = input.nextInt(); 11 | if(number % 2 == 0) { 12 |     System.out.println("even"); 13 | } else { 14 |     System.out.println("odd"); 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.2: Spikey.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named Spikey that prints the following output: 2 | 3 | \/ 4 | \\// 5 | \\\/// 6 | ///\\\ 7 | //\\ 8 | /\ 9 | */ 10 | public class Spikey { 11 |     public static void main(String[] args) { 12 |         System.out.println("  \\/"); 13 |         System.out.println(" \\\\//"); 14 |         System.out.println("\\\\\\///"); 15 |         System.out.println("///\\\\\\"); 16 |         System.out.println(" //\\\\"); 17 |         System.out.println("  /\\"); 18 |     } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.14: nestedNumbers3.java: -------------------------------------------------------------------------------- 1 | /*Modify your code from the previous problem to produce the following output: 2 | 3 | 4 | 999999999888888887777777666666555554444333221 5 | 999999999888888887777777666666555554444333221 6 | 999999999888888887777777666666555554444333221 7 | 999999999888888887777777666666555554444333221 8 | 9 | */ 10 | 11 | for(int i = 1; i <= 4; i++) { 12 |     for(int j = 9; j >= 1; j--) { 13 |         for(int k = j - 1; k >= 0; k--) 14 |             System.out.print(j); 15 |     } 16 |     System.out.println(); 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.5: ifElseMystery1.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method. 2 | 3 | public static void ifElseMystery1(int x, int y) { 4 | int z = 4; 5 | if (z <= x) { 6 | z = x + 1; 7 | } else { 8 | z = z + 9; 9 | } 10 | if (z <= y) { 11 | y++; 12 | } 13 | System.out.println(z + " " + y); 14 | } 15 | For each call below, indicate what output is produced.*/ 16 | 17 | ifElseMystery1(3, 20); 13 21 18 | ifElseMystery1(4, 5); 5 6 19 | ifElseMystery1(5, 5); 6 5 20 | ifElseMystery1(6, 10); 7 11 21 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.14: cylinderSurfaceArea.java: -------------------------------------------------------------------------------- 1 | /*Write a method called cylinderSurfaceArea that accepts a radius and height (both real numbers) as parameters and returns the surface 2 | area of a cylinder with those dimensions. For example, the call cylinderSurfaceArea(3.0, 4.5) should return 141.3716694115407. 3 | The formula for the surface area of a cylinder with radius r and height h is the following: 4 | surface area = 2πr2 + 2πrh 5 | */ 6 | public static double cylinderSurfaceArea(double r, double h) { 7 |     return 2 * Math.PI * r * r + 2 * Math.PI * r * h; 8 | } 9 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.19: printReverse.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printReverse that accepts a String as its parameter and prints the characters in opposite order. 2 | For example, a call of printReverse("hello there!"); should print the following output: 3 | 4 | !ereht olleh 5 | 6 | If the empty string is passed, no output is produced. Your method should produce a complete line of output.*/ 7 | public static void printReverse(String string) { 8 |     for(int i = string.length() - 1; i >= 0; i--) { 9 |         System.out.print(string.charAt(i)); 10 |     } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.21: capitalLetter.java: -------------------------------------------------------------------------------- 1 | /*Write an if statement that tests to see whether a String stored in a variable named phrase begins with a capital letter. If the 2 | string begins with a capital letter, print capital . If not, print not capital . Use at least one method call from the Character 3 | class in your solution. You may assume that the string is non-empty (contains at least one character).*/ 4 | 5 | if(Character.isUpperCase(phrase.charAt(0))) { 6 |     System.out.println("capital"); 7 | } else { 8 |     System.out.println("not capital"); 9 | } 10 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.18: arraySwap.java: -------------------------------------------------------------------------------- 1 | /*Why does a method to swap two array elements work correctly when a method to swap two integer values does not? 2 | a. Unlike integers, arrays are objects and use reference semantics. 3 | b. Because of a bug in Java. 4 | c. Because arrays use more memory than primitive values. 5 | d. Because arrays are slower and more inefficient than primitives, so swapping is possible. 6 | e. Changes to an array parameter's elements will not be seen in the original array by the caller.*/ 7 | a. Unlike integers, arrays are objects and use reference semantics. 8 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.1: fractionSum.java: -------------------------------------------------------------------------------- 1 | /*Write a method called fractionSum that accepts an integer parameter n and returns as a double the sum of the first n terms of the sequence: 2 | 3 | fraction sum equation 4 | 5 | In other words, the method should generate the following sequence: 6 | 7 | 1 + (1/2) + (1/3) + (1/4) + (1/5) + ... 8 | 9 | You may assume that the parameter n is non-negative.*/ 10 | 11 | public static double fractionSum(int n) { 12 |     double sum = 0.0; 13 |     for(int i = 1; i <= n; i++) { 14 |         sum += 1.0/i; 15 |     } 16 | return sum; 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.23: lastFirst.java: -------------------------------------------------------------------------------- 1 | /*Write a method named lastFirst that accepts a string as its parameter representing a person's first and last name. The method 2 | should return the person's last name followed by the first initial and a period. For example, the call lastFirst("Marla Singer") 3 | should return "Singer, M." . You may assume that the string passed consists of exactly two words separated by a single space.*/ 4 | 5 | public static String lastFirst(String name) { 6 | String[] parts = name.split(" "); 7 | return parts[1] + ", " + parts[0].charAt(0) + "."; 8 | } 9 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.1: lastIndexOf.java: -------------------------------------------------------------------------------- 1 | /*Write a method named lastIndexOf that accepts an array of integers and an integer value as its parameters and returns the last 2 | index at which the value occurs in the array. The method should return -1 if the value is not found. For example, in the list 3 | containing {74, 85, 102, 99, 101, 85, 56}, the last index of the value 85 is 5.*/ 4 | public static int lastIndexOf(int[] array, int value) { 5 | for(int i = array.length - 1; i >= 0; i--) { 6 | if(array[i] == value) { 7 | return i; 8 | } 9 | } 10 | return -1; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Self-Check 3G.4: drawLineRectErrors.java: -------------------------------------------------------------------------------- 1 | /*The following code attempts to draw a black rectangle from (10, 20) to (50, 40) with a line across its diagonal: 2 | 3 | 4 | DrawingPanel panel = new DrawingPanel(200, 100); 5 | Graphics g = panel.getGraphics(); 6 | g.drawRect(10, 20, 50, 40); 7 | g.drawLine(10, 20, 50, 40); 8 | However, it is incorrect. Find the mistakes and correct the code. Type the correct code below.*/ 9 | 10 | DrawingPanel panel = new DrawingPanel(200, 100); 11 | Graphics g = panel.getGraphics(); 12 | g.drawRect(10, 20, 40, 20); 13 | g.drawLine(10, 20, 50, 40); 14 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.21: fourScore.java: -------------------------------------------------------------------------------- 1 | /*Given the following code, what indexes must be passed to the substring method to produce the new String with the value 2 | "SCORE"? What indexes to substring produce "fouryears"? 3 | 4 | 5 | // index 012345678901234567890123456789 6 | String quote = "Four score and seven years ago"; 7 | String expr1 = quote.substring(a, b).toUpperCase(); // "SCORE" 8 | String expr2 = quote.toLowerCase().substring(c, d) + quote.substring(e, f); // "fouryears" 9 | */ 10 | 11 | a 5 12 | b 10 13 | c 0 14 | d 4 15 | e 21 16 | f 26 17 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.29: averageLength.java: -------------------------------------------------------------------------------- 1 | /*Write a method averageLength of code that computes and returns the average String length of the elements of an array of Strings. 2 | For example, if the array contains {"belt", "hat", "jelly", "bubble gum"}, the average length returned should be 5.5. 3 | Assume that the array has at least one element.*/ 4 | 5 | public static double averageLength(String[] array) { 6 | double totalLength = 0.0; 7 | for(int i = 0; i < array.length; i++) { 8 | totalLength += array[i].length(); 9 | } 10 | return totalLength / array.length; 11 | } 12 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.35: unknown.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following unknown method? 2 | 3 | 4 | public class Strange { 5 | public static final int MAX = 5; 6 | 7 | public static void unknown() { 8 | int number = 0; 9 | for (int count = MAX; count >= 1; count--) { 10 | number += (count * count); 11 | } 12 | 13 | System.out.println("The result is: " + number); 14 | } 15 | 16 | public static void main(String[] args) { 17 | unknown(); 18 | } 19 | }*/ 20 | output: The result is: 55 21 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.10: max.java: -------------------------------------------------------------------------------- 1 | /*Write a method called max that accepts an array of integers as a parameter and returns the maximum value in the array. For example, if 2 | the array passed stores {12, 7, -1, 25, 3, 9}, your method should return 25. You may assume that the array contains at least one element. 3 | Your method should not modify the elements of the array.*/ 4 | public static int max(int[] data) { 5 |     int temp = data[0]; 6 |     for(int i = 0; i < data.length; i++) { 7 |         if(data[i] > temp) { 8 |             temp = data[i]; 9 |         } 10 |     } 11 |     return temp; 12 | } 13 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.25: arrayMystery2.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method, mystery. 2 | 3 | 4 | public static void mystery2(int[] a, int[] b) { 5 | for (int i = 0; i < a.length; i++) { 6 | a[i] = a[2 * i % a.length] - b[3 * i % b.length]; 7 | } 8 | } 9 | What are the values of the elements in array a1 after the following code executes? 10 | 11 | 12 | int[] a1 = {2, 4, 6, 8, 10, 12, 14, 16}; 13 | int[] a2 = {1, 1, 2, 3, 5, 8, 13, 21}; 14 | mystery2(a1, a2); 15 | */ 16 | a1[0] 1 17 | a1[1] 3 18 | a1[2] -3 19 | a1[3] 13 20 | a1[4] -4 21 | a1[5] -24 22 | a1[6] -6 23 | a1[7] -14 24 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.31: arrayCodeTracing2d.java: -------------------------------------------------------------------------------- 1 | /*What are the values of the elements in the array numbers after the following code is executed? 2 | 3 | 4 | int[][] numbers = new int[3][4]; 5 | for (int r = 0; r < numbers.length; r++) { 6 | for (int c = 0; c < numbers[0].length; c++) { 7 | numbers[r][c] = r + c; 8 | } 9 | }*/ 10 | numbers[0][0] 0 11 | numbers[0][1] 1 12 | numbers[0][2] 2 13 | numbers[0][3] 3 14 | numbers[1][0] 1 15 | numbers[1][1] 2 16 | numbers[1][2] 3 17 | numbers[1][3] 4 18 | numbers[2][0] 2 19 | numbers[2][1] 3 20 | numbers[2][2] 4 21 | numbers[2][3] 5 22 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.18: MyProgram-errors.java: -------------------------------------------------------------------------------- 1 | /*The following program contains three errors. Correct the errors and submit a working version of the program. 2 | 3 | public MyProgram { 4 | public static void main(String[] args) { 5 | System.out.println("This is a test of the") 6 | System.out.Println("emergency broadcast system."); 7 | } 8 | }*/ 9 | 10 | public class MyProgram { 11 |     public static void main(String[] args) { 12 |         System.out.println("This is a test of the"); 13 |         System.out.println("emergency broadcast system."); 14 |     } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.13: printElements.java: -------------------------------------------------------------------------------- 1 | /*Write code that uses a for loop to print each element of an array named data that contains five integers. If the array contains 2 | the elements [14, 5, 27, -3, 2598], then your code should produce the following output: 3 | 4 | element [0] is 14 5 | element [1] is 5 6 | element [2] is 27 7 | element [3] is -3 8 | element [4] is 2598 9 | 10 | Once your code works for the array of size 5, generalize the code so that it works for an array of any length.*/ 11 | for(int i = 0; i < data.length; i++) { 12 |     System.out.println("element [" + i + "] is " + data[i]); 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Self-Check 12.14: mystery5.java: -------------------------------------------------------------------------------- 1 | /*For each call to the following method, indicate what value is returned: 2 | 3 | public int mystery5(int x, int y) { 4 | if (x < 0) { 5 | return -mystery5(-x, y); 6 | } else if (y < 0) { 7 | return -mystery5(x, -y); 8 | } else if (x == 0 && y == 0) { 9 | return 0; 10 | } else { 11 | return 100 * mystery5(x / 10, y / 10) + 10 * (x % 10) + y % 10; 12 | } 13 | }*/ 14 | 15 | mystery5(5, 7) 57 16 | mystery5(12, 9) 1029 17 | mystery5(-7, 4) -74 18 | mystery5(-23, -48) 2438 19 | mystery5(128, 343) 132483 20 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Self-Check 12.5: mystery3.java: -------------------------------------------------------------------------------- 1 | /*For each call to the following method, indicate what console output is produced: 2 | 3 | public void mystery3(int n) { 4 | if (n <= 0) { 5 | System.out.print("*"); 6 | } else if (n % 2 == 0) { 7 | System.out.print("("); 8 | mystery3(n - 1); 9 | System.out.print(")"); 10 | } else { 11 | System.out.print("["); 12 | mystery3(n - 1); 13 | System.out.print("]"); 14 | } 15 | }*/ 16 | mystery3(0); * 17 | mystery3(1); [*] 18 | mystery3(2); ([*]) 19 | mystery3(4); ([([*])]) 20 | mystery3(5); [([([*])])] 21 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.26: arrayMystery3.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method, mystery. 2 | 3 | 4 | public static void mystery3(int[] data, int x, int y) { 5 | data[data[x]] = data[y]; 6 | data[y] = x; 7 | } 8 | What are the values of the elements in array numbers after the following code executes? 9 | 10 | int[] numbers = {3, 7, 1, 0, 25, 4, 18, -1, 5}; 11 | mystery3(numbers, 3, 1); 12 | mystery3(numbers, 5, 6); 13 | mystery3(numbers, 8, 4); 14 | */ 15 | numbers[0] 7 16 | numbers[1] 3 17 | numbers[2] 1 18 | numbers[3] 0 19 | numbers[4] 8 20 | numbers[5] 18 21 | numbers[6] 5 22 | numbers[7] -1 23 | numbers[8] 5 24 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.14: pow2.java: -------------------------------------------------------------------------------- 1 | /*Write a method named pow2 (a variation of the previous pow exercise) that accepts a real number base and an integer exponent 2 | as parameters and returns the base raised to the given power. Your code should work for both positive and negative exponents. 3 | For example, the call pow2(2.0, -2) returns 0.25. Do not use Math.pow in your solution.*/ 4 | public static double pow2(double base, int exp) { 5 | double pow = 1.0; 6 | 7 | for(int i = 1; i <= Math.abs(exp); i++) { 8 | pow *= base; 9 | } 10 | if(exp < 0) { 11 | return 1 / pow; 12 | } 13 | return pow; 14 | } 15 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.11: contribution.java: -------------------------------------------------------------------------------- 1 | /*Rewrite the code below by factoring to eliminate redundancy. Your code must produce the same results. To simplify things, you 2 | may assume that the user always types 1 or 2 for the multiplier.*/ 3 | 4 | System.out.print("Is your money multiplied 1 or 2 times? "); 5 | int times = console.nextInt(); 6 | System.out.print("And how much are you contributing? "); 7 | int donation = console.nextInt(); 8 | if (times == 1) { 9 |     sum = sum + donation; 10 |     count1++;    11 | } else { 12 |     sum = sum + 2 * donation; 13 |     count2++; 14 | } 15 | total = total + donation; 16 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.27: arrayMystery4.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method: 2 | 3 | 4 | public static int arrayMystery4(int[] list) { 5 | int x = 0; 6 | for (int i = 1; i < list.length; i++) { 7 | int y = list[i] - list[0]; 8 | if (y > x) { 9 | x = y; 10 | } 11 | } 12 | return x; 13 | } 14 | For each array below, indicate what value would be returned if the method mystery were called and passed that array as its parameter.*/ 15 | 16 | 17 | {5} 0 18 | {3, 12} 9 19 | {4, 2, 10, 8} 6 20 | {1, 9, 3, 5, 7} 8 21 | {8, 2, 10, 4, 10, 9} 2 22 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.9: Egg.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named Egg that displays the following output: 2 | 3 | _______ 4 | / \ 5 | / \ 6 | -"-'-"-'-"- 7 | \ / 8 | \_______/ 9 | 10 | */ 11 | 12 | public class Egg { 13 |     public static void main(String[] args) { 14 |         System.out.println("  _______"); 15 |         System.out.println(" /       \\"); 16 |         System.out.println("/         \\"); 17 |         System.out.println("-\"-'-\"-'-\"-"); 18 |         System.out.println("\\         /"); 19 |         System.out.println(" \\_______/"); 20 |     } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.13: nestedNumbers2.java: -------------------------------------------------------------------------------- 1 | /*Modify your code from the previous problem to produce the following output: 2 | 3 | 4 | 99999888887777766666555554444433333222221111100000 5 | 99999888887777766666555554444433333222221111100000 6 | 99999888887777766666555554444433333222221111100000 7 | 99999888887777766666555554444433333222221111100000 8 | 99999888887777766666555554444433333222221111100000 9 | 10 | */ 11 | for(int i = 1; i <= 5; i++) { 12 |     for(int j = 9; j >= 0; j--) { 13 |         for(int k = 1; k <= 5; k++) 14 |             System.out.print(j); 15 |     } 16 |     System.out.println(); 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/4.20: numUnique.java: -------------------------------------------------------------------------------- 1 | /*Write a method named numUnique that takes three integers as parameters and that returns the number of unique integers among the 2 | three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, 3 | the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.*/ 4 | public static int numUnique(int a, int b, int c) { 5 | if(a == b && b != c || a == c && b!= a || b == c && c != a)  6 | return 2; 7 | if(a == b && b == c && c == a) 8 | return 1; 9 | return 3; 10 | } 11 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.3: countInRange.java: -------------------------------------------------------------------------------- 1 | /*Write a method called countInRange that accepts an array of integers, a minimum value, and a maximum value as parameters and 2 | returns the count of how many elements from the array fall between the minimum and maximum (inclusive). 3 | 4 | For example, in the array {14, 1, 22, 17, 36, 7, -43, 5}, there are four elements whose values fall between 4 and 17.*/ 5 | public static int countInRange(int[] array, int min, int max) { 6 | int temp = 0; 7 | for(int i = 0; i < array.length; i++) { 8 | if(array[i] <= max && array[i] >= min) { 9 | temp++; 10 | } 11 | } 12 | return temp; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.4: Odds.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following program? 2 | 3 | 4 | public class Odds { 5 | public static void main(String[] args) { 6 | printOdds(3); 7 | printOdds(17 / 2); 8 | 9 | int x = 25; 10 | printOdds(37 - x + 1); 11 | } 12 | 13 | public static void printOdds(int n) { 14 | for (int i = 1; i <= n; i++) { 15 | int odd = 2 * i - 1; 16 | System.out.print(odd + " "); 17 | } 18 | System.out.println(); 19 | } 20 | }*/ 21 | 22 | 1 3 5 23 | 1 3 5 7 9 11 13 15 24 | 1 3 5 7 9 11 13 15 17 19 21 23 25 25 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.19: gpaMessage.java: -------------------------------------------------------------------------------- 1 | /*The following code was intended to print a message when the double gpa variable's value is 3.2, but it actually produces the wrong output. 2 | Fix the code to print the expected message. 3 | 4 | (The idea here is that the expression 3.2 * 3 in Java does not exactly equal 9.6. You should leave in the computation of the credits 5 | variable and should still make your test examine that variable's value, rather than just directly testing the gpa variable itself.)*/ 6 | 7 | double credits = gpa * 3; 8 | if (Math.round(credits) == 10) { 9 |     System.out.println("You earned enough credits."); 10 | } 11 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.16b: equalsStrings.java: -------------------------------------------------------------------------------- 1 | /*Write a method called equals that takes in two string arrays and returns true if they are equal; that is, if both arrays have 2 | the same length and contain equivalent string values at each index. 3 | 4 | (If you like, you may look at the equals method developed in section 7.2 of the Building Java Programs textbook as a reference. 5 | The version in that book section compares arrays of integers instead of strings.)*/ 6 | public static boolean equals(String[] a, String[] b) { 7 | if(a.length == b.length) { 8 | if(Arrays.equals(a, b)) { 9 | return true; 10 | } 11 | } 12 | return false; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.14: TestOfKnowledge.java: -------------------------------------------------------------------------------- 1 | /*What series of println statements would produce the following output? 2 | 3 | This is a test of your 4 | knowledge of "quotes" used 5 | in 'string literals.' 6 | 7 | You're bound to "get it right" 8 | if you read the section on 9 | ''quotes.'' 10 | */ 11 | System.out.println("This is a test of your"); 12 | System.out.println("knowledge of \"quotes\" used"); 13 | System.out.println("in 'string literals.'"); 14 | System.out.println(); 15 | System.out.println("You're bound to \"get it right\""); 16 | System.out.println("if you read the section on"); 17 | System.out.println("''quotes.''"); 18 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.9: lastDigit .java: -------------------------------------------------------------------------------- 1 | /*Write a method named lastDigit that returns the last digit of an integer. For example, lastDigit(3572) should return 2. 2 | It should work for negative numbers as well. For example, lastDigit(-947) should return 7. 3 | 4 | Call Value Returned 5 | lastDigit(3572) 2 6 | lastDigit(-947) 7 7 | lastDigit(6) 6 8 | lastDigit(35) 5 9 | lastDigit(123456) 6 10 | 11 | (Hint: This is a short method. You may not use a String to solve this problem.*/ 12 | 13 | public static int lastDigit(int number) { 14 |     return Math.abs(number % 10); 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.17: countQuarters.java: -------------------------------------------------------------------------------- 1 | /*Write a method called countQuarters that takes an int representing a number of cents as a parameter and returns the number 2 | of quarter coins represented by that many cents. Don't count any whole dollars, because those would be dispensed as dollar 3 | bills. For example, countQuarters(64) would return 2, because 2 quarters make 50 cents, with 14 extra left over. 4 | A call of countQuarters(1278) would return 3, because after the 12 dollars are taken out, 3 quarters remain in the 78 cents left.*/ 5 | 6 | public static int countQuarters(int cents) { 7 | cents = cents % 100; 8 | return cents / 25; 9 | } 10 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.10: percentEven.java: -------------------------------------------------------------------------------- 1 | /*Write a method called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers 2 | in the array as a real number. For example, if the array stores the elements {6, 2, 9, 11, 3}, then your method should return 40.0. 3 | If the array contains no even elements or no elements at all, return 0.0.*/ 4 | public static double percentEven(int[] array) { 5 | double num = 0; 6 | if(array.length < 1) { 7 | return 0.0; 8 | } 9 | for(int i = 0; i < array.length; i++) { 10 | if(array[i] % 2 == 0) { 11 | num++; 12 | } 13 | } 14 | return (num * 100) / array.length; 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.28: arrayMystery5.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method: 2 | 3 | 4 | public static void arrayMystery5(int[] nums) { 5 | for (int i = 0; i < nums.length - 1; i++) { 6 | if (nums[i] > nums[i + 1]) { 7 | nums[i + 1]++; 8 | } 9 | } 10 | } 11 | For each array below, indicate what the array's contents would be after the method mystery were called and passed that array as its parameter.*/ 12 | {8} [8] 13 | {14, 7} [14, 8] 14 | {7, 1, 3, 2, 0, 4} [7, 2, 3, 3, 1, 4] 15 | {10, 8, 9, 5, 5} [10, 9, 9, 6, 6] 16 | {12, 11, 10, 10, 8, 7} [12, 12, 11, 11, 9, 8] 17 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.13: pay.java: -------------------------------------------------------------------------------- 1 | /*Write a method named pay that accepts a real number for a TA's salary and an integer for the number of hours the TA worked 2 | this week, and returns how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. 3 | 4 | The TA should receive "overtime" pay of 1 ½ normal salary for any hours above 8. For example, the call pay(4.00, 11) should 5 | return (4.00 * 8) + (6.00 * 3) or 50.0.*/ 6 | 7 | public static double pay(double salary, int hours) { 8 |     if(hours <= 8) { 9 |         return salary * hours; 10 |     } else { 11 |         return (salary * 8) + (salary * 1.5) * (hours - 8); 12 |     }    13 | } 14 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.4: daysInMonth.java: -------------------------------------------------------------------------------- 1 | /*Write a method named daysInMonth that accepts a month (an integer between 1 and 12) as a parameter and returns the number of 2 | days in that month in this year. For example, the call daysInMonth(9) would return 30 because September has 30 days. Assume that 3 | the code is not being run during a leap year (that February always has 28 days).*/ 4 | 5 | public static int daysInMonth(int month) { 6 | if(month == 1 || month == 3 || month == 5 || month == 7 || 7 | month == 8 || month == 10 || month == 12) { 8 | return 31; 9 | } else if (month == 2) { 10 | return 28; 11 | } else { 12 | return 30; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.16: countFactors.java: -------------------------------------------------------------------------------- 1 | /*Consider the task of writing a method named countFactors that accepts an integer (assumed to be positive) as its parameter and 2 | returns a count of its positive factors. For example, the six factors of 12 are 1, 2, 3, 4, 6, and 12, so the call countFactors(12) 3 | should return 6. The following is an attempt at solving the problem, but it is incorrect. Determine what is wrong with the code, and 4 | submit a corrected version that works properly.*/ 5 | 6 | public static int countFactors(int n) { 7 | int k = 0; 8 | for(int i = 1; i <= n; i++) { 9 | if(n % i == 0) 10 | k++; 11 | } 12 | return k; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.29: printNumOdd.java: -------------------------------------------------------------------------------- 1 | /*Consider the following Java method, which is written incorrectly. Under what cases will the method print the correct answer, and 2 | when will it print an incorrect answer? What should be changed to fix the code? 3 | (For an extra challenge, can you think of a way to write the code correctly without any if/else statements?)*/ 4 | 5 | // This method should return how many of its three 6 | // arguments are odd numbers. 7 | public static void printNumOdd(int n1, int n2, int n3) { 8 |     int count = Math.abs(n1) % 2 + Math.abs(n2) % 2 + Math.abs(n3) % 2; 9 |     System.out.println(count + " of the 3 numbers are odd."); 10 | } 11 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Self-Check 3G.3: fillRectErrors.java: -------------------------------------------------------------------------------- 1 | /*The following code attempts to draw a filled black outer rectangle with a white filled inner circle inside it: 2 | 3 | 4 | DrawingPanel panel = new DrawingPanel(200, 100); 5 | Graphics g = panel.getGraphics(); 6 | g.setColor(Color.WHITE); 7 | g.fillOval(10, 10, 50, 50); 8 | g.setColor(Color.BLACK); 9 | g.fillRect(10, 10, 50, 50); 10 | However, it is incorrect. Find the mistakes and correct the code below.*/ 11 | 12 | DrawingPanel panel = new DrawingPanel(200, 100); 13 | Graphics g = panel.getGraphics(); 14 | g.setColor(Color.BLACK); 15 | g.fillRect(10, 10, 50, 50); 16 | g.setColor(Color.WHITE); 17 | g.fillOval(10, 10, 50, 50); 18 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.36: loopTableConstant.java: -------------------------------------------------------------------------------- 1 | /*Assume that you have a variable called line that will take on the values 1, 2, 3, 4, and so on, and a class constant named 2 | SIZE that takes two values. You are going to formulate expressions in terms of line and SIZE that will yield different 3 | sequences of numbers of characters. The first row is filled in for you as an example. Fill in the solution boxes below, 4 | indicating an expression that will generate each sequence. Your answers must be in the exact 5 | format 'coefficient1 * line + (coefficient2 * SIZE + offset)' in that order to be counted as correct.*/ 6 | 1. 4 * line + (3 * SIZE) 7 | 2. line - (2 * SIZE) + 3 8 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.17: cumulativeProduct.java: -------------------------------------------------------------------------------- 1 | /*Write code to produce a cumulative product by multiplying together many numbers that are read from the console. Match the following format: 2 | 3 | How many numbers? 4 4 | Next number --> 7 5 | Next number --> 2 6 | Next number --> 3 7 | Next number --> 15 8 | Product = 630 9 | */ 10 |     Scanner console = new Scanner(System.in); 11 |     System.out.print("How many numbers? "); 12 | int number = console.nextInt(); 13 | int k = 1; 14 | for(int i = 1; i <= number; i++) { 15 | System.out.print("Next number --> "); 16 | int num = console.nextInt(); 17 | k *= num; 18 | } 19 | System.out.println("Product = " + k); 20 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.30: isPalindrome.java: -------------------------------------------------------------------------------- 1 | /*Write a method isPalindrome that accepts an array of Strings as its argument and returns true if that array is a palindrome (if it reads the same forwards as backwards) 2 | and /false if not. For example, the array {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} is a palindrome, so passing that array to your method would return true. 3 | Arrays with zero or one element are considered to be palindromes.*/ 4 | public static boolean isPalindrome(String[] array) { 5 | int l = array.length - 1; 6 | for(int i = 0; i < array.length / 2; i++) { 7 | if(!array[i].equals(array[l - i])) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.1: binaryNumbers.java: -------------------------------------------------------------------------------- 1 | /*Why do computers use binary numbers? 2 | 3 | a. Because there are 10 types of people: Those who understand binary, and those who don't. 4 | b. It is easier to build electronic devices reliably if they only have to distinguish between two electric states. 5 | c. It is impossible to build a computer that uses a different number base than binary. 6 | d. It makes the computer faster and more efficient than other number bases. 7 | e. At the time when computers were invented, humans only knew about the numbers 0 and 1.*/ 8 | 9 | b. It is easier to build electronic devices reliably if they only have to distinguish between two electric states. 10 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.11: average.java: -------------------------------------------------------------------------------- 1 | /*Write a method called average that computes the average (arithmetic mean) of all elements in an array of integers and returns 2 | the answer as a double. For example, if the array passed contains the values [1, -2, 4, -4, 9, -6, 16, -8, 25, -10], the calculated 3 | average should be 2.5. Your method accepts an array of integers as its parameter and returns the average. 4 | You may assume that the array contains at least one element. Your method should not modify the elements of the array.*/ 5 | 6 | public static double average(int[] data) { 7 |     int sum = 0; 8 |     for(int d : data) { 9 |         sum += d; 10 |     } 11 |     return (double) sum / data.length; 12 | } 13 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.10: numbersOutput60.java: -------------------------------------------------------------------------------- 1 | /*It's common to print a rotating, increasing list of single-digit numbers at the start of a program's output as a visual 2 | guide to number the columns of the output to follow. With this in mind, write nested for loops to produce the following 3 | output, with each line 60 characters wide: 4 | 5 | | | | | | | 6 | 123456789012345678901234567890123456789012345678901234567890 7 | 8 | */ 9 | for(int k = 1; k<= 6; k++) { 10 | for(int i = 1; i <= 9; i++)  11 | System.out.print(" "); 12 | System.out.print("|"); 13 | } 14 | System.out.println(); 15 | for(int j = 1; j <= 60; j++)  16 | System.out.print(j%10); 17 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.1: printNumbers.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printNumbers that accepts a maximum number as a parameter and prints each number from 1 up to that 2 | maximum, inclusive, boxed by square brackets. For example, consider the following calls: 3 | 4 | 5 | printNumbers(15); 6 | printNumbers(5); 7 | These calls should produce the following output: 8 | 9 | [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] 10 | [1] [2] [3] [4] [5] 11 | You may assume that the value passed to printNumbers is 1 or greater.*/ 12 | 13 | public static void printNumbers(int number) { 14 |      15 |     for(int i = 1; i <= number; i++) { 16 |         System.out.print("[" + i + "] "); 17 |     } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.5: Weird.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following program? 2 | 3 | 4 | public class Weird { 5 | public static void main(String[] args) { 6 | int number = 8; 7 | halfTheFun(11); 8 | halfTheFun(2 - 3 + 2 * 8); 9 | halfTheFun(number); 10 | System.out.println("number = " + number); 11 | } 12 | 13 | public static void halfTheFun(int number) { 14 | number = number / 2; 15 | for (int count = 1; count <= number; count++) { 16 | System.out.print(count + " "); 17 | } 18 | System.out.println(); 19 | } 20 | }*/ 21 | 22 | 1 2 3 4 5 23 | 1 2 3 4 5 6 7 24 | 1 2 3 4 25 | number = 8 26 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.20: charMystery.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following program? 2 | 3 | public class CharMystery { 4 | public static void printRange(char startLetter, char endLetter) { 5 | for (char letter = startLetter; letter <= endLetter; letter++) { 6 | System.out.print(letter); 7 | } 8 | System.out.println(); 9 | } 10 | public static void main(String[] args) { 11 | printRange('e', 'g'); 12 | printRange('n', 's'); 13 | printRange('z', 'a'); 14 | printRange('q', 'r'); 15 | } 16 | }*/ 17 | 18 | printRange('e', 'g'); efg 19 | printRange('n', 's'); nopqrs 20 | printRange('z', 'a'); 21 | printRange('q', 'r'); qr 22 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.4: isSorted.java: -------------------------------------------------------------------------------- 1 | /*Write a static method named isSorted that accepts an array of doubles as a parameter and returns true if the list is in sorted 2 | (nondecreasing) order and false otherwise. For example, if arrays named list1 and list2 store {16.1, 12.3, 22.2, 14.4} and 3 | {1.5, 4.3, 7.0, 19.5, 25.1, 46.2} respectively, the calls isSorted(list1) and isSorted(list2) should return false and true 4 | respectively. Assume the array has at least one element. A one-element array is considered to be sorted.*/ 5 | public static boolean isSorted(double[] array) { 6 | for(int i = 1; i < array.length; i++) { 7 | if(array[i] < array[i - 1]) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.17: allLess.java: -------------------------------------------------------------------------------- 1 | /*Write a method called allLess that accepts two arrays of integers and returns true if each element in the first array is less 2 | than the element at the same index in the second array. Your method should return false if the arrays are not the same length. 3 | For example, if the two arrays passed are {45, 20, 300} and {50, 41, 600}, your method should return true. If the arrays are not 4 | the same length, you should always return false.*/ 5 | public static boolean allLess(int[] x, int[] y) { 6 | if(x.length != y.length) { 7 | return false; 8 | } 9 | for(int i = 0; i < x.length; i++) { 10 | if(x[i] > y[i]) { 11 | return false; 12 | } 13 | } 14 | return true; 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.15: printDesign.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printDesign that produces the following output. Use nested for loops to capture the structure of the figure. 2 | 3 | -----1----- 4 | ----333---- 5 | ---55555--- 6 | --7777777-- 7 | -999999999- 8 | 9 | */ 10 | public static void printDesign() { 11 |     for(int i = 1; i <= 9; i+=2) { 12 |         for(int j = 0; j < (11 - i) / 2; j++) 13 |             System.out.print("-"); 14 |              15 |         for(int j = 0; j < i; j++) 16 |             System.out.print(i); 17 |              18 |         for(int j = 0; j < (11 - i) / 2; j++) 19 |             System.out.print("-"); 20 |              21 |         System.out.println(); 22 |     }     23 | } 24 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.12: Temperature-errors.java: -------------------------------------------------------------------------------- 1 | /*The following program contains several errors. Correct the errors and submit a working version of the program. 2 | The corrected version of the program should produce the following output: 3 | 4 | Body temp in C is: 37.0 5 | */ 6 | public class Temperature { 7 |     public static void main(String[] args) { 8 |         double tempf = 98.6; 9 |         double tempc = 0.0; 10 |         ftoc(tempf, tempc); 11 |          12 |     } 13 | 14 |     // converts Fahrenheit temperatures to Celsius 15 |     public static void ftoc(double tempf, double tempc) { 16 |         tempc = (tempf - 32) * 5 / 9; 17 |         System.out.println("Body temp in C is: " + tempc); 18 |     } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.26: RobertPaulson.java: -------------------------------------------------------------------------------- 1 | /*Write code that prompts the user for a phrase and a number of times to repeat it, then prints the phrase the phrase that many times. Here is an example dialogue with the user: 2 | 3 | What is your phrase? His name is Robert Paulson 4 | How many times should I repeat it? 3 5 | His name is Robert Paulson 6 | His name is Robert Paulson 7 | His name is Robert Paulson 8 | */ 9 | Scanner reader = new Scanner(System.in); 10 | System.out.print("What is your phrase? "); 11 | String phrase = reader.nextLine(); 12 | System.out.print("How many times should I repeat it? "); 13 | int repeat = reader.nextInt(); 14 | for(int i = 0; i < repeat; i++) { 15 |     System.out.println(phrase); 16 | } 17 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.18: wordCount.java: -------------------------------------------------------------------------------- 1 | /*Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is 2 | a sequence of one or more nonspace characters (any character other than ' '). For example, the call wordCount("hello") should 3 | return 1, the call wordCount("how are you?") should return 3, the call wordCount(" this string has wide spaces ") 4 | should return 5, and the call wordCount(" ") should return 0.*/ 5 | 6 | public static int wordCount(String string) { 7 | String[] str = string.split(" "); 8 | int i = 0; 9 | for(String s : str) { 10 | if(s.length() > 0) { 11 | i++; 12 | } 13 | } 14 | return i; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.16: withoutPrintStatements.java: -------------------------------------------------------------------------------- 1 | /*Rewrite the following code as a series of equivalent System.out.println statements 2 | (i.e., without any System.out.print statements): 3 | 4 | System.out.print("Twas "); 5 | System.out.print("brillig and the "); 6 | System.out.println(" "); 7 | System.out.print(" slithy toves did"); 8 | System.out.print(" "); 9 | System.out.println("gyre and"); 10 | System.out.println( "gimble"); 11 | System.out.println(); 12 | System.out.println( "in the wabe." ); 13 | */ 14 | System.out.println("Twas brillig and the"); 15 | System.out.println(" slithy toves did gyre and"); 16 | System.out.println("gimble"); 17 | System.out.println(); 18 | System.out.println("in the wabe."); 19 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.7: kthLargest.java: -------------------------------------------------------------------------------- 1 | /*Write a method called kthLargest that accepts an integer k and an array a as its parameters and returns the element such that 2 | k elements have greater or equal value. If k = 0, return the largest element; if k = 1, return the second largest element, and so on. 3 | 4 | For example, if the array passed contains the values {74, 85, 102, 99, 101, 56, 84} and the integer k passed is 2, your method 5 | should return 99 because there are two values at least as large as 99 (101 and 102). 6 | 7 | Assume that 0 <= k < a.length. (Hint: Consider sorting the array, or a copy of the array first.)*/ 8 | public static int kthLargest(int k, int[] a) { 9 | Arrays.sort(a); 10 | return a[a.length - (k + 1)]; 11 | } 12 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.7: arrayBugs.java: -------------------------------------------------------------------------------- 1 | /*What is wrong with the following code? Correct the bugs to produce the following expected output: 2 | 3 | first = [3, 7] 4 | second = [3, 7] 5 | They contain the same elements.*/ 6 | int[] first = new int[2]; 7 | first[0] = 3; 8 | first[1] = 7; 9 | int[] second = new int[2]; 10 | second[0] = 3; 11 | second[1] = 7; 12 | 13 | // print the array elements 14 | System.out.println("first  = " + Arrays.toString(first)); 15 | System.out.println("second = " + Arrays.toString(second)); 16 | 17 | // see if the elements are the same 18 | if (Arrays.equals(first, second)) { 19 |     System.out.println("They contain the same elements."); 20 | } else { 21 |     System.out.println("The elements are different."); 22 | } 23 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.30: nestedLoops.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following program? 2 | 3 | 4 | public class Loops { 5 | public static void main(String[] args) { 6 | for (int i = 1; i <= 10; i++) { 7 | for (int j = 1; j <= 10 - i; j++) { 8 | System.out.print(" "); 9 | } 10 | for (int j = 1; j <= 2 * i - 1; j++) { 11 | System.out.print("*"); 12 | } 13 | System.out.println(); 14 | } 15 | } 16 | }*/ 17 | * 18 | *** 19 | ***** 20 | ******* 21 | ********* 22 | *********** 23 | ************* 24 | *************** 25 | ***************** 26 | ******************* 27 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.9: waveNumbers40.java: -------------------------------------------------------------------------------- 1 | /*Write for loops to produce the following output, with each line 40 characters wide: 2 | 3 | ---------------------------------------- 4 | _-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^- 5 | 1122334455667788990011223344556677889900 6 | ---------------------------------------- 7 | */ 8 | for(int i = 1; i <= 40; i++) { 9 | System.out.print("-"); 10 | } 11 | System.out.println(); 12 | for(int j = 1; j <= 10; j++) { 13 | System.out.print("_-^-"); 14 | } 15 | System.out.println(); 16 | for(int j = 0; j < 2; j++) { 17 | for(int i = 1; i <= 10; i++) { 18 | System.out.print(i%10); 19 | System.out.print(i%10); 20 | } 21 | } 22 | System.out.println(); 23 | for(int i = 1; i <= 40; i++) 24 | System.out.print("-"); 25 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.4: Difference.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named Difference that prints the following output: 2 | 3 | What is the difference between 4 | a ' and a "? Or between a " and a \"? 5 | 6 | One is what we see when we're typing our program. 7 | The other is what appears on the "console." 8 | */ 9 | 10 | public class Difference { 11 |     public static void main(String[] args) { 12 |         System.out.println("What is the difference between\n" 13 |                            + "a ' and a \"?  Or between a \" and a \\\"?\n"); 14 |         System.out.println("One is what we see when we're typing our program."); 15 |         System.out.println("The other is what appears on the \"console.\""); 16 |     } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.23: scannerTokensDouble.java: -------------------------------------------------------------------------------- 1 | /*Given the following code fragment, describe what will happen when the user types each of the following values. If the code will read the value successfully, describe the value that will be stored in the variable money. If it will not, write exception . (Make sure to write a value of the proper type, such as 12.0 rather than 12 for a double.) 2 | 3 | 4 | Scanner console = new Scanner(System.in); 5 | System.out.print("How much money do you have? "); 6 | double money = console.nextDouble();*/ 7 | 8 | 34.50 34.5 9 | 6 6.0 10 | $25.00 exception 11 | million exception 12 | 100*5 exception 13 | 600x000 exception 14 | none exception 15 | 645 645.0 16 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.1: displacement.java: -------------------------------------------------------------------------------- 1 | /*In physics, a common useful equation for finding the position s of a body in linear motion at a given time t, based on 2 | its initial position s0, initial velocity v0, and rate of acceleration a, is the following: 3 | 4 | s = s0 + v0 t + ½ at2 5 | 6 | Write code to declare variables for s0 with a value of 12.0, v0 with a value of 3.5, a with a value of 9.8, and t with a value 7 | of 10, and then write the code to compute s on the basis of these values. At the end of your code, print the value of your 8 | variable s to the console./* 9 | 10 | double s = 12.0; 11 | double v = 3.5; 12 | double a = 9.8; 13 | int t = 10; 14 | double position = s + v * t + 0.5 * a * t * t; 15 | System.out.println(position); 16 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.22: Tricky.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following program? You may wish to draw a structure diagram first. 2 | 3 | 4 | public class Tricky { 5 | public static void main(String[] args) { 6 | message1(); 7 | message2(); 8 | System.out.println("Done with main."); 9 | } 10 | ​ 11 | public static void message1() { 12 | System.out.println("This is message1."); 13 | } 14 | ​ 15 | public static void message2() { 16 | System.out.println("This is message2."); 17 | message1(); 18 | System.out.println("Done with message2."); 19 | } 20 | }*/ 21 | This is message1. 22 | This is message2. 23 | This is message1. 24 | Done with message2. 25 | Done with main. 26 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.12: priceIsRight.java: -------------------------------------------------------------------------------- 1 | /*Write a method priceIsRight that accepts an array of integers bids and an integer price as parameters. The method returns the element 2 | in the bids array that is closest in value to price without being larger than price. For example, if bids stores the elements {200, 300, 3 | 250, 999, 40}, then priceIsRight(bids, 280) should return 250, since 250 is the bid closest to 280 without going over 280. 4 | If all bids are larger than price, then your method should return -1.*/ 5 | 6 | public int priceIsRight(int[] bids, int price) { 7 | int bid = -1; 8 | 9 | for(int i = 0; i < bids.length; i++) { 10 | if(price - bids[i] >= 0 && bids[i] > bid) 11 | bid = bids[i]; 12 | } 13 | 14 | return bid; 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.12: DoubleSlash.java: -------------------------------------------------------------------------------- 1 | /*What is the output from the following Java program? (Assume that a tab is expanded into eight spaces.) 2 | 3 | 4 | public class Letter { 5 | public static void main(String[] args) { 6 | System.out.println("Dear \"DoubleSlash\" magazine,"); 7 | System.out.println(); 8 | System.out.println("\tYour publication confuses me. Is it"); 9 | System.out.println("a \\\\ slash or a //// slash?"); 10 | System.out.println("\nSincerely,"); 11 | System.out.println("Susan \"Suzy\" Smith"); 12 | } 13 | }*/ 14 | 15 | Dear "DoubleSlash" magazine, 16 | 17 | Your publication confuses me. Is it 18 | a \\ slash or a //// slash? 19 | 20 | Sincerely, 21 | Susan "Suzy" Smith 22 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Exercise 12.2: writeNums.java: -------------------------------------------------------------------------------- 1 | /*Write a method writeNums that accepts an integer parameter n and prints the first n integers starting with 1 in sequential order, 2 | separated by commas. For example, the following calls produce the following output: 3 | 4 | Call Output 5 | writeNums(5); 1, 2, 3, 4, 5 6 | writeNums(12); 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 7 | Your method should throw an IllegalArgumentException if passed a value less than 1. Note that the output does not advance to the next line.*/ 8 | public static void writeNums(int n) { 9 | if(n < 1) { 10 | throw new IllegalArgumentException(); 11 | } else if(n == 1) { 12 | System.out.print("1"); 13 | } else { 14 | writeNums(n-1); 15 | System.out.print(", " + n); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.8: median.java: -------------------------------------------------------------------------------- 1 | /*Write a method called median that accepts an array of integers as its argument and returns the median of the numbers in the array. 2 | The median is the number that will appear in the middle if you arrange the elements in order. Assume that the array is of odd size 3 | (so that one sole element constitutes the median) and that the numbers in the array are between 0 and 99 inclusive. 4 | 5 | For example, the median of {5, 2, 4, 17, 55, 4, 3, 26, 18, 2, 17} is 5, and the median of 6 | {42, 37, 1, 97, 1, 2, 7, 42, 3, 25, 89, 15, 10, 29, 27} is 25. 7 | 8 | (Hint: You may wish to look at the Tally program from earlier in this chapter for ideas.)*/ 9 | public static int median(int[] array) { 10 | Arrays.sort(array); 11 | return array[array.length/2]; 12 | } 13 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.7: Mantra.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named Mantra that produces the following output. Remove its redundancy by 2 | adding a method. 3 | 4 | There's one thing every coder must understand: 5 | The System.out.println command. 6 | 7 | There's one thing every coder must understand: 8 | The System.out.println command. 9 | */ 10 | 11 | public class Mantra { 12 |     public static void main(String[] args) { 13 |         mantra(); 14 |     } 15 |     public static void mantra() { 16 |         String thing = "There's one thing every coder must understand:"; 17 |         String command = "The System.out.println command."; 18 |         String mantra = thing + "\n" + command; 19 |         System.out.print(mantra + "\n\n" + mantra); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.18: doubleSumError.java: -------------------------------------------------------------------------------- 1 | /*The expression (0.2 + 1.2 + 2.2 + 3.2) should equal 6.8, but in Java it does not. Why not? 2 | a. The programmer forgot to cast the expression to type double, so the result is inaccurate. 3 | b. Real numbers are represented as imprecise floating-point numbers in the computer, and the limited precision led to a roundoff error. 4 | c. Those numbers are integers in Java, so the sum is 6. 5 | d. Java has a bug making it unable to add real numbers accurately, unlike other superior languages such as C++. 6 | e. Java is unable to perform a + expression involving so many numbers, so the code does not compile.*/ 7 | b. Real numbers are represented as imprecise floating-point numbers in the computer, and the limited precision led to a roundoff error. 8 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.25: SumNumbers.java: -------------------------------------------------------------------------------- 1 | /*Consider the following program. Modify the given SumNumbers code to use a Scanner to prompt the user for the values of low and high. The following is a sample execution in which the user asks for the sum of the values 1 through 10: 2 | 3 | low? 1 4 | high? 10 5 | sum = 55 6 | */ 7 | public class SumNumbers { 8 |     public static void main(String[] args) { 9 |         Scanner input = new Scanner(System.in); 10 |         System.out.print("low? "); 11 |         int low = input.nextInt(); 12 |         System.out.print("high? "); 13 |         int high = input.nextInt(); 14 |         int sum = 0; 15 |         for (int i = low; i <= high; i++) { 16 |             sum += i; 17 |         } 18 |         System.out.println("sum = " + sum); 19 |     } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.4: Oops4-errors.java: -------------------------------------------------------------------------------- 1 | /*The following program contains 7 errors. Correct the errors and submit a working version of the program. The corrected version 2 | of the program should produce the following output: 3 | 4 | a is the smallest! 5 | */ 6 | public class Oops4 { 7 |     public static void main(String[] args) { 8 |         int a = 7, b = 42; 9 |         minimum(a, b); 10 |         int smaller = 0; 11 |         if (smaller <= a) { 12 |             System.out.println("a is the smallest!"); 13 |         } 14 |     } 15 | 16 |     public static void minimum(int a, int b) { 17 |         if (a < b) { 18 |             int smaller = a; 19 |         } else if(a >= b) { 20 |             int smaller = b; 21 |         } else { 22 |         int smaller; 23 |     } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.8: ScannerLogicError.java: -------------------------------------------------------------------------------- 1 | /*The following code contains a logic error. Examine the code and figure out the case(s) in which the code would print something 2 | that is untrue about the number that was entered. Then correct the logic error in the code. You should retain the original printed 3 | messages (and not add any new ones), but make them print at appropriate times such that the message printed is always a true 4 | statement about the integer typed.*/ 5 | 6 | Scanner console = new Scanner(System.in); 7 | System.out.print("Type a number: "); 8 | int number = console.nextInt(); 9 | if (number % 2 == 0) { 10 |     if (number % 3 == 0) { 11 |         System.out.println("Divisible by 6."); 12 |     } 13 |     } else { 14 |         System.out.println("Odd."); 15 |     } 16 | -------------------------------------------------------------------------------- /Chapter 12- Recursion/Exercise 12.1: starString.java: -------------------------------------------------------------------------------- 1 | /*Write a method starString that accepts an integer parameter n and returns a string of stars (asterisks) 2n long (i.e., 2 to the nth power). 2 | For example: 3 | 4 | Call Output Reason 5 | starString(0); "*" 20 = 1 6 | starString(1); "**" 21 = 2 7 | starString(2); "****" 22 = 4 8 | starString(3); "********" 23 = 8 9 | starString(4); "****************" 24 = 16 10 | You should throw an IllegalArgumentException if passed a value less than 0.*/ 11 | public static String starString(int n) { 12 | if(n < 0) { 13 | throw new IllegalArgumentException(); 14 | } else if(n == 0) { 15 | return "*"; 16 | } else { 17 | return starString(n - 1) + starString(n - 1); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.16: triangleArea.java: -------------------------------------------------------------------------------- 1 | /*Write a method called triangleArea that accepts the three side lengths of a triangle (all real numbers) as parameters and 2 | returns the area of a triangle with those side lengths. For example, the call triangleArea(8, 5.2, 7.1) should return 18.151176098258745. 3 | To compute the area, use Heron's formula, which states that the area of a triangle whose three sides have lengths a, b, and c, is the following. 4 | The formula is based on the computed value s, a length equal to half the perimeter of the triangle: 5 | 6 | area = √ (s (s-a)(s-b)(s-c)) 7 | where s = (a + b + c) / 2 8 | */ 9 | public static double triangleArea(double a, double b, double c) { 10 |     double s = (a + b + c) / 2; 11 |     return Math.sqrt(s * (s - a) * (s - b) * (s - c)); 12 | } 13 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.12: Triangle.java: -------------------------------------------------------------------------------- 1 | /*Using the DrawingPanel class, write a Java class named Triangle that produces the following figure: 2 | 3 | -size: 600x200 4 | -background color: yellow 5 | -line color: blue 6 | -vertical spacing between lines: 10 px 7 | The diagonal lines connect at the bottom in the middle.*/ 8 | 9 | public class Triangle { 10 |     public static void main(String[] args) { 11 |         DrawingPanel panel = new DrawingPanel(600, 200); 12 |         panel.setBackground(Color.YELLOW); 13 |         Graphics g = panel.getGraphics(); 14 |         g.setColor(Color.BLUE); 15 |         g.drawLine(0, 0, 300, 200); 16 | g.drawLine(300, 200, 600, 0); 17 |         for(int i = 1; i < 20; i++) { 18 |             g.drawLine(15 * i, 10 * i, 600 - 15 * i, 10 * i); 19 |         } 20 |     } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.36: jaggedArray.java: -------------------------------------------------------------------------------- 1 | /*Write a piece of code that constructs a jagged two-dimensional array of integers named jagged with five rows and an increasing 2 | number of columns in each row, such that the first row has one column, the second row has two, the third has three, and so on. 3 | The array elements should have increasing values in top-to-bottom, left-to-right order (also called row-major order). 4 | In other words, the array's contents should be the following: 5 | 6 | 1 7 | 2, 3 8 | 4, 5, 6 9 | 7, 8, 9, 10 10 | 11, 12, 13, 14, 15 11 | */ 12 | int[][] jagged = new int[5][]; 13 | int temp = 1; 14 | for(int i = 0; i < jagged.length; i++) { 15 | jagged[i] = new int[i + 1]; 16 | for(int j = 0; j < jagged[i].length; j++) { 17 | jagged[i][j] = temp; 18 | temp++; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.5: MuchBetter.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named MuchBetter that prints the following output: 2 | 3 | A "quoted" String is 4 | 'much' better if you learn 5 | the rules of "escape sequences." 6 | Also, "" represents an empty String. 7 | Don't forget: use \" instead of " ! 8 | '' is not the same as " 9 | */ 10 | 11 | public class MuchBetter { 12 |     public static void main(String[] args) { 13 |         System.out.println("A \"quoted\" String is\n'much' better if you learn\n" 14 |                            + "the rules of \"escape sequences.\"\n" 15 |                            + "Also, \"\" represents an empty String.\n" 16 |                            + "Don't forget: use \\\" instead of \" !\n" 17 |                            + "'' is not the same as \""); 18 |     } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.20: StarFigure.java: -------------------------------------------------------------------------------- 1 | /*Write a program in a class named StarFigure that produces the following output using for loops. 2 | 3 | ////////////////\\\\\\\\\\\\\\\\ 4 | ////////////********\\\\\\\\\\\\ 5 | ////////****************\\\\\\\\ 6 | ////************************\\\\ 7 | ******************************** 8 | 9 | */ 10 | public class StarFigure { 11 | 12 | public static void main(String[] args) { 13 | for (int i = 1; i <= 5; i++) { 14 |             for (int j = 1; j <= 20 - 4 * i; j++) { 15 |                 System.out.print("/"); 16 |              17 | } 18 | for (int j = 1; j <= 8 * i - 8; j++) { 19 |             System.out.print("*"); 20 | } 21 | for (int j = 1; j <= 20 - 4 * i; j++) { 22 |             System.out.print("\\"); 23 | } 24 | System.out.println(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.3: WellFormed.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named WellFormed that prints the following output: 2 | 3 | A well-formed Java program has 4 | a main method with { and } 5 | braces. 6 | 7 | A System.out.println statement 8 | has ( and ) and usually a 9 | String that starts and ends 10 | with a " character. 11 | (But we type \" instead!) 12 | 13 | */ 14 | public class WellFormed { 15 |     public static void main(String [] args) { 16 |         System.out.println("A well-formed Java program has\na main method with { and }\nbraces.\n"); 17 |         System.out.println("A System.out.println statement\nhas ( and ) and usually a"); 18 |         System.out.println("String that starts and ends\nwith a \" character."); 19 |         System.out.println("(But we type \\\" instead!)"); 20 |     } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.24: secondHalfLetters.java: -------------------------------------------------------------------------------- 1 | /*Write a method named secondHalfLetters that accepts a string as its parameter and returns an integer representing how many of letters 2 | in the string come from the second half of the alphabet (that is, have values of 'n' through 'z' inclusive). Compare case-insensitively, 3 | such that uppercase values of 'N' through 'Z' also count. For example, the call secondHalfLetters("ruminates") should return 5 because 4 | the 'r', 'u', 'n', 't', and 's' come from the second half of the alphabet. You may assume that every character in the string is a letter.*/ 5 | 6 | public static int secondHalfLetters(String s) { 7 | int count = 0; 8 | for(int i = 0; i < s.length(); i++) { 9 | if(Character.toLowerCase(s.charAt(i)) >= 'n') { 10 | count++; 11 | } 12 | } 13 | return count; 14 | } 15 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.11a: Stairs2.java: -------------------------------------------------------------------------------- 1 | /*Modify your Stairs program from the previous exercise to make a new class Stairs2 that draws the output shown below. Modify only the body of your loop. 2 | (You may want to make a new table to find the expressions for x, y, width, and height for each new output.) 3 | 4 | (You don't need to include any import statements at the top of your program.) (The next exercise is a modified version of this 5 | program, so you can use the code you write here as a starting point for that exercise.)*/ 6 | 7 | public class Stairs2 { 8 |     public static void main(String[] args) { 9 |         DrawingPanel panel = new DrawingPanel(110, 110); 10 |         Graphics g = panel.getGraphics(); 11 |         for (int i = 1; i <= 10; i++) { 12 |             g.drawRect(5, 10 * i - 5, 110 - 10 * i, 10); 13 |         } 14 |     } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.3: fibonacci.java: -------------------------------------------------------------------------------- 1 | /*The Fibonacci numbers are a sequence of integers in which the first two elements are 1, and each following element is the sum 2 | of the two preceding elements. The mathematical definition of each kth Fibonacci number is the following: 3 | 4 | F(k): 5 | k > 2 : F(k-1) + F(k-2) 6 | k <= 2 : 1 7 | 8 | The first 12 Fibonacci numbers are: 9 | 10 | 1 1 2 3 5 8 13 21 34 55 89 144 11 | Write a piece of code that uses a for loop to compute and print the first 12 Fibonacci numbers. (You may include other code, 12 | such as declaring variables before the loop, if you like.)*/ 13 | 14 | int f0 = 1; 15 | int f1 = 1; 16 | 17 | System.out.print(f0 + " "); 18 | System.out.print(f1 + " "); 19 | 20 | for(int fk = 2; fk <= 144; fk = f1 + f0) { 21 | System.out.print(fk + " "); 22 | f0 = f1; 23 | f1 = fk; 24 | } 25 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.37: loopTableSlashes .java: -------------------------------------------------------------------------------- 1 | /*Consider the following pattern of output consisting of 6 lines of repeated characters \, !, and /. Fill in the following equation for the number of each character relative to the line number for each type of character. We suggest that you write a table that lists the number of each character on each line that you can use to help find the equations from the output, as described in Chapter 2. 2 | 3 | !!!!!!!!!!!!!!!!!!!!!! 4 | \\!!!!!!!!!!!!!!!!!!// 5 | \\\\!!!!!!!!!!!!!!//// 6 | \\\\\\!!!!!!!!!!////// 7 | \\\\\\\\!!!!!!//////// 8 | \\\\\\\\\\!!////////// 9 | Compute the value of A, B, C, and D in the equations below. Assume that the lines are numbered from 1 through 6. 10 | 11 | number of \ = A * line + B 12 | number of ! = C * line + D 13 | */ 14 | 15 | A 2 16 | B -2 17 | C -4 18 | D 26 19 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.11b: Stairs3.java: -------------------------------------------------------------------------------- 1 | /*Modify your Stairs program from the previous exercise to make a new class Stairs3 that draws the output shown below. Modify only 2 | the body of your loop. (You may want to make a new table to find the expressions for x, y, width, and height for each new output.) 3 | 4 | (You don't need to include any import statements at the top of your program.) (The next exercise is a modified version of this 5 | program, so you can use the code you write here as a starting point for that exercise.)*/ 6 | 7 | public class Stairs3 { 8 |     public static void main(String[] args) { 9 |         DrawingPanel panel = new DrawingPanel(110, 110); 10 |         Graphics g = panel.getGraphics(); 11 |         for (int i = 1; i <= 10; i++) { 12 |             g.drawRect(105 - i * 10 , i * 10 - 5,10 * i, 10); 13 |         } 14 |     } 15 | } 16 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.11c: Stairs4.java: -------------------------------------------------------------------------------- 1 | /*Modify your Stairs program from the previous exercise to make a new class Stairs4 that draws the output shown below. Modify only 2 | the body of your loop. (You may want to make a new table to find the expressions for x, y, width, and height for each new output.) 3 | 4 | (You don't need to include any import statements at the top of your program.) (The next exercise is a modified version of this 5 | program, so you can use the code you write here as a starting point for that exercise.)*/ 6 | 7 | public class Stairs4 { 8 |     public static void main(String[] args) { 9 |         DrawingPanel panel = new DrawingPanel(110, 110); 10 |         Graphics g = panel.getGraphics(); 11 |         for (int i = 1; i <= 10; i++) { 12 |             g.drawRect(i * 10 - 5 , i * 10 - 5,110 - i * 10, 10); 13 |         } 14 |     } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.29: LotsOfErrors-errors.java: -------------------------------------------------------------------------------- 1 | /*The following program contains at least 10 errors. Correct the errors and submit a working version of the program. 2 | 3 | public class LotsOf Errors { 4 | public static main(String args) { 5 | System.println(Hello, world!); 6 | message() 7 | } 8 | 9 | public static void message { 10 | System.out println("This program surely cannot "; 11 | System.out.println("have any "errors" in it"); 12 | }*/ 13 | public class LotsOfErrors { 14 |     public static void main(String [] args) { 15 |         System.out.println("Hello, world!"); 16 |         message(); 17 |     } 18 | 19 |     public static void message() { 20 |         System.out.println("This program surely cannot "); 21 |         System.out.println("have any \"errors\" in it"); 22 |     } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.19: stringExpressions.java: -------------------------------------------------------------------------------- 1 | /*Assuming that the following variables have been declared, 2 | 3 | 4 | // index 0123456789012345 5 | String str1 = "Frodo Baggins"; 6 | String str2 = "Gandalf the GRAY"; 7 | Evaluate the following expressions. Make sure to give a value of the appropriate type (such as including quotes around a 8 | String or apostrophes around a char).*/ 9 | 10 | 11 | str1.length() 13 12 | str1.charAt(7) 'a' 13 | str2.charAt(0) 'G' 14 | str1.indexOf("o") 2 15 | str2.toUpperCase() "GANDALF THE GRAY" 16 | str1.toLowerCase().indexOf("B") -1 17 | str1.substring(4) "o Baggins" 18 | str2.substring(3, 14) "dalf the GR" 19 | str2.replace("a", "oo") "Goondoolf the GRAY" 20 | str2.replace("gray", "white") "Gandalf the GRAY" 21 | "str1".replace("r", "range") "strange1" 22 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.7: xo.java: -------------------------------------------------------------------------------- 1 | /*Write a static method named xo that accepts an integer size as a parameter and prints a square of size by size characters, where 2 | all characters are "o" except that an "x" pattern of "x" characters has been drawn from the corners of the square. In other words, 3 | on the first line, the first and last characters are "x"; on the second line, the second and second-from-last characters are "x"; 4 | and so on. If 0 or less is passed for the size, no output should be produced.*/ 5 | 6 | public static void xo(int x) { 7 | int a = 0; 8 | int z = x - 1; 9 | for(int i = 0; i < x; i++) { 10 | for(int j = 0; j < x; j++) { 11 | if(j == a || j == z) { 12 | System.out.print("x"); 13 | } else { 14 | System.out.print("o"); 15 | } 16 | } 17 | System.out.println(); 18 | a++; 19 | z--; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.18: pseudocodeWindow.java: -------------------------------------------------------------------------------- 1 | /*Write a pseudocode algorithm that will produce the following figure as output: 2 | 3 | +===+===+ 4 | | | | 5 | | | | 6 | | | | 7 | +===+===+ 8 | | | | 9 | | | | 10 | | | | 11 | +===+===+ 12 | 13 | (Since this is just pseudo-code, Practice-It is not able to verify that your solution is "correct". But you can submit an 14 | answer anyway to show that you completed this exercise. Any non-trivial answer will be accepted.)*/ 15 | 16 | System.out.println("+===+===+"); 17 | System.out.println("| | |"); 18 | System.out.println("| | |"); 19 | System.out.println("| | |"); 20 | System.out.println("+===+===+"); 21 | System.out.println("| | |"); 22 | System.out.println("| | |"); 23 | System.out.println("| | |"); 24 | System.out.println("+===+===+"); 25 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.13: mathExpressions.java: -------------------------------------------------------------------------------- 1 | /*Evaluate the following expressions. Make sure to give a value of the appropriate type (such as including a decimal point 2 | in a double).*/ 3 | 4 | Math.abs(-1.6) 1.6 5 | Math.abs(2 + -4) 2 6 | Math.pow(6, 2) 36.0 7 | Math.pow(5 / 2, 6) 64.0 8 | Math.ceil(9.1) 10.0 9 | Math.ceil(115.8) 116.0 10 | Math.max(7, 4) 7 11 | Math.min(8, 3 + 2) 5 12 | Math.min(-2, -5) -5 13 | Math.sqrt(64) 8.0 14 | Math.sqrt(76 + 45) 11.0 15 | 100 + Math.log10(100) 102.0 16 | 13 + Math.abs(-7) - Math.pow(2, 3) + 5 17.0 17 | Math.sqrt(16) * Math.max(Math.abs(-5), Math.abs(-3)) 20.0 18 | 7 - 2 + Math.log10(1000) + Math.log(Math.pow(Math.E, 5)) 13.0 19 | Math.max(18 - 5 + Math.random(), Math.ceil(4.6 * 3)) 14.0 20 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.21: processName.java: -------------------------------------------------------------------------------- 1 | /*Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter 2 | his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first 3 | and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as 4 | necessary. Here is a sample dialogue with the user: 5 | 6 | Please enter your full name: Sammy Jankis 7 | Your name in reverse order is Jankis, Sammy 8 | 9 | */ 10 | public static void processName(Scanner console) { 11 |     System.out.print("Please enter your full name: "); 12 |     String name = console.nextLine(); 13 |     String[] parts = name.split(" "); 14 |     System.out.println("Your name in reverse order is " + parts[1] + ", " + parts[0]); 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.12: traversal.java: -------------------------------------------------------------------------------- 1 | /*Which of the following best describes an array traversal? 2 | a. Constructing a new empty array. 3 | b. Changing the elements from positive to negative. 4 | c. Changing the elements into the opposite order. 5 | d. A sequential processing of each of an array's elements. 6 | e. Deleting values from an array.*/ 7 | d. A sequential processing of each of an array's elements. 8 | 9 | /*Which of the following are examples of problems that can be solved by traversing an array? 10 | a. Searching an array for a given value. 11 | b. Printing an array's elements. 12 | c. Swapping the first and last values of an array. 13 | d. Comparing two arrays for equality. 14 | e. Examining the value of the first element of the array.*/ 15 | a. Searching an array for a given value. 16 | b. Printing an array's elements. 17 | d. Comparing two arrays for equality. 18 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.20: ReferenceMystery2.java: -------------------------------------------------------------------------------- 1 | /*The following program produces 4 lines of output. Write each line of output below as it would appear on the console. 2 | 3 | 4 | import java.util.*; // for Arrays class 5 | ​ 6 | public class ReferenceMystery2 { 7 | public static void main(String[] args) { 8 | int x = 1; 9 | int[] a = new int[2]; 10 | mystery(x, a); 11 | System.out.println(x + " " + Arrays.toString(a)); 12 | x--; 13 | a[1] = a.length; 14 | mystery(x, a); 15 | System.out.println(x + " " + Arrays.toString(a)); 16 | } 17 | 18 | public static void mystery(int x, int[] list) { 19 | list[x]++; 20 | x++; 21 | System.out.println(x + " " + Arrays.toString(list)); 22 | } 23 | }*/ 24 | 25 | line 1 2 {0, 1} 26 | line 2 1 {0, 1} 27 | line 3 1 {1, 2} 28 | line 4 0 [1, 2} 29 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.27: medianOf3.java: -------------------------------------------------------------------------------- 1 | /*The following method attempts to return the median (middle) of three integer values, but it contains logic errors. In what cases 2 | does the method return an incorrect result? How can the code be fixed? Determine what is wrong with the code, and submit a corrected 3 | version that works properly.*/ 4 | 5 | public static int medianOf3(int n1, int n2, int n3) { 6 | if (n1 < n2 && n1 < n3) { 7 |         if (n2 < n3) { 8 |             return n2; 9 |         } else { 10 |             return n3; 11 |         } 12 |     } else if (n2 < n1 && n2 < n3) { 13 |         if (n1 < n3) { 14 |             return n1; 15 |         } else { 16 |             return n3; 17 |         } 18 |     } else { // (n3 < n1 && n3 < n2) 19 |         if (n1 < n2) { 20 |             return n1; 21 |         } else { 22 |             return n2; 23 |         } 24 |     } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.26: Confusing.java: -------------------------------------------------------------------------------- 1 | /*What is the output from the following Java program? 2 | 3 | public class Confusing { 4 | public static void method1() { 5 | System.out.println("I am method 1."); 6 | } 7 | public static void method2() { 8 | method1(); 9 | System.out.println("I am method 2."); 10 | } 11 | public static void method3() { 12 | method2(); 13 | System.out.println("I am method 3."); 14 | method1(); 15 | } 16 | public static void main(String[] args) { 17 | method1(); 18 | method3(); 19 | method2(); 20 | method3(); 21 | } 22 | }*/ 23 | I am method 1. 24 | I am method 1. 25 | I am method 2. 26 | I am method 3. 27 | I am method 1. 28 | I am method 1. 29 | I am method 2. 30 | I am method 1. 31 | I am method 2. 32 | I am method 3. 33 | I am method 1. 34 | 35 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.5: javaVsClass.java: -------------------------------------------------------------------------------- 1 | /*What is the difference between the file MyProgram.java and the file MyProgram.class? 2 | 3 | a. The programmer writes the .class file first, and the .java file is generated automatically later. 4 | b. The .class file is for object-oriented programming and the .java file is for procedural programming. 5 | c. A .java file is a much larger binary file and a .class file is a smaller compressed version. 6 | d. A .java file contains code written in the Java language, and a .class file contains code written in the C++ language. 7 | e. MyProgram.java is a source code file typed by the programmer, and MyProgram.class is a compiled executable class 8 | file that is run by the computer.*/ 9 | e. MyProgram.java is a source code file typed by the programmer, and MyProgram.class is a compiled executable class 10 | file that is run by the computer. 11 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.35: arrayMystery2d.java: -------------------------------------------------------------------------------- 1 | /*Consider the following method: 2 | 3 | 4 | public static void mystery2d(int[][] a) { 5 | for (int r = 0; r < a.length; r++) { 6 | for (int c = 0; c < a[0].length - 1; c++) { 7 | if (a[r][c + 1] > a[r][c]) { 8 | a[r][c] = a[r][c + 1]; 9 | } 10 | } 11 | } 12 | } 13 | If a two-dimensional array named numbers is initialized to store the following integers, what are its contents after the call shown? 14 | 15 | 16 | int[][] numbers = { 17 | {3, 4, 5, 6}, 18 | {4, 5, 6, 7}, 19 | {5, 6, 7, 8} 20 | }; 21 | mystery2d(numbers); 22 | */ 23 | 24 | numbers[0][0] 4 25 | numbers[0][1] 5 26 | numbers[0][2] 6 27 | numbers[0][3] 6 28 | numbers[1][0] 5 29 | numbers[1][1] 6 30 | numbers[1][2] 7 31 | numbers[1][3] 7 32 | numbers[2][0] 6 33 | numbers[2][1] 7 34 | numbers[2][2] 8 35 | numbers[2][3] 8 36 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.3: Oops3-errors.java: -------------------------------------------------------------------------------- 1 | /*The following program contains 9 errors. Correct the errors and submit a working version of the program. 2 | The corrected version of the program should produce the following output: 3 | 4 | x = 10.01 and y = 8.0 5 | x = 10.01 and y = 867.5309 6 | The value from main is: 867.5309 7 | z = 5 8 | */ 9 | 10 | public class Oops3 { 11 |     public static void main(String[] args) { 12 |         double bubble = 867.5309; 13 |         double x = 10.01; 14 |         double y = 8.0; 15 |         int z = 5; 16 |         printer(x, y); 17 |         printer(x, bubble); 18 |         System.out.println("The value from main is: " + bubble); 19 |         System.out.println("z = " + z); 20 |     } 21 | 22 |     public static void printer(double x, double y) { 23 |          24 |         System.out.println("x = " + x + " and y = " + y); 25 |          26 |          27 |     } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.19: ReferenceMystery1.java: -------------------------------------------------------------------------------- 1 | /*The following program produces 4 lines of output. Write each line of output below as it would appear on the console. 2 | 3 | 4 | import java.util.*; // for Arrays class 5 | ​ 6 | public class ReferenceMystery1 { 7 | public static void main(String[] args) { 8 | int x = 0; 9 | int[] a = new int[4]; 10 | x++; 11 | 12 | mystery(x, a); 13 | System.out.println(x + " " + Arrays.toString(a)); 14 | 15 | x++; 16 | mystery(x, a); 17 | System.out.println(x + " " + Arrays.toString(a)); 18 | } 19 | 20 | public static void mystery(int x, int[] a) { 21 | x++; 22 | a[x]++; 23 | System.out.println(x + " " + Arrays.toString(a)); 24 | } 25 | }*/ 26 | 27 | line 1 2 {0, 0, 1, 0} 28 | line 2 1 {0, 0, 1, 0} 29 | line 3 3 {0, 0, 1, 1} 30 | line 4 2 {0, 0, 1, 1} 31 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.6: Meta.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program called Meta whose output is the text that would be the source code of a Java program named 2 | Hello that prints "Hello, world!" as its output: 3 | 4 | 5 | public class Hello { 6 | public static void main(String[] args) { 7 | System.out.println("Hello, world!"); 8 | } 9 | } 10 | 11 | Your program must produce exactly the output shown in order to pass (using exactly four spaces for each increment of 12 | indentation in the output).*/ 13 | 14 | public class Meta { 15 |     public static void main(String[] args) { 16 |         System.out.println("public class Hello {"); 17 |         System.out.println("    public static void main(String[] args) {"); 18 |         System.out.println("        System.out.println(\"Hello, world!\");"); 19 |         System.out.println("    }"); 20 |         System.out.println("}"); 21 |     } 22 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.17: Commentary.java: -------------------------------------------------------------------------------- 1 | /*What is the output of the following program? Note that the program contains several comments. 2 | 3 | 4 | public class Commentary { 5 | public static void main(String[] args) { 6 | System.out.println("some lines of code"); 7 | System.out.println("have // characters on them"); 8 | System.out.println("which means "); // that they are comments 9 | // System.out.println("written by the programmer."); 10 | 11 | System.out.println("lines can also"); 12 | System.out.println("have /* and */ characters"); 13 | /* System.out.println("which represents"); 14 | System.out.println("a multi-line style"); 15 | */ System.out.println("of comment."); 16 | } 17 | }*/ 18 | some lines of code 19 | have // characters on them 20 | which means 21 | lines can also 22 | have /* and */ characters 23 | of comment. 24 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.26: getGradePreconditions.java: -------------------------------------------------------------------------------- 1 | /*Consider a method getGrade that accepts an integer representing a student's grade percentage in a course and returns that student's numerical course grade: 2 | 3 | public static double getGrade(int percentage) { 4 | ... 5 | } 6 | 7 | The grade can be between 0.0 (failing) and 4.0 (perfect). 8 | 9 | Which of the following are precondition(s) that are appropriate for this method? Check all that apply. 10 | 11 | a. The parameter's value must be greater than or equal to 0. 12 | b. The parameter's value must be between 0.0 and 4.0. 13 | c. The parameter can be an integer or a real number. 14 | d. The parameter's value must be less than or equal to 100. 15 | e. The parameter must be a letter grade of 'A', 'B', 'C', or 'D'.*/ 16 | a. The parameter's value must be greater than or equal to 0. 17 | d. The parameter's value must be less than or equal to 100. 18 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.12: spending.java: -------------------------------------------------------------------------------- 1 | /*The following code is poorly structured. Rewrite it so that it has a better structure and avoids redundancy. To help eliminate 2 | redundancy, convert the code into a method named spending that accepts two parameters: a Scanner for the console, and a String 3 | for a single person's name, and prints the appropriate information about that person's bills. Your method could be called twice 4 | (once for John and once for Jane) to replicate the original code's behavior.*/ 5 | 6 | public static void spending(Scanner console, String name) { 7 |     System.out.print("How much will " + name + " be spending? "); 8 |     double amount = console.nextDouble(); 9 |      10 |     int numBills = (int) (amount / 20.0); 11 |     if (numBills * 20.0 < amount) { 12 |         numBills++; 13 |     } 14 |     System.out.println(); 15 |     System.out.println(name + " needs " + numBills + " bills"); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.20: stringExpressions2.java: -------------------------------------------------------------------------------- 1 | /*Assuming that the following variables have been declared, 2 | 3 | 4 | String str1 = "Q.E.D."; 5 | String str2 = "Arcturan Megadonkey"; 6 | String str3 = "Sirius Cybernetics Corporation"; 7 | Evaluate the following expressions. Make sure to give a value of the appropriate type (such as including quotes around a String).*/ 8 | 9 | str1.length() 6 10 | str2.length() 19 11 | str1.toLowerCase() "q.e.d." 12 | str2.toUpperCase() "ARCTURAN MEGADONKEY" 13 | str1.substring(2, 4) "E." 14 | str2.substring(10, 14) "egad" 15 | str1.indexOf("D") 4 16 | str1.indexOf(".") 1 17 | str2.indexOf("donkey") 13 18 | str3.indexOf("X") -1 19 | str2 + str3.charAt(17) "Arcturan Megadonkeys" 20 | str3.substring(9, str3.indexOf("e")) "b" 21 | str3.substring(7, 12) "Cyber" 22 | str2.toLowerCase().substring(9, 13) + str3.substring(18, str3.length() - 7) "mega Corp" 23 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.17: padString.java: -------------------------------------------------------------------------------- 1 | /*Write a method padString that accepts two parameters: a String and an integer representing a length. The method should pad 2 | the parameter string with spaces until its length is the given length. For example, padString("hello", 8) should return " hello". 3 | (This sort of method is useful when trying to print output that lines up horizontally.) If the string's length is already at least as 4 | long as the length parameter, your method should return the original string. For example, padString("congratulations", 10) 5 | would return "congratulations".*/ 6 | 7 | public static String padString(String string, int length) { 8 |     if(length == string.length()) { 9 |         return string; 10 |     } else { 11 |         int l = (length - string.length()); 12 |         String s = ""; 13 |         for(int i = 0; i < l; i++) { 14 |             s+=" "; 15 |         } 16 |         return s + string; 17 |     } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.2: printPowersOf2 .java: -------------------------------------------------------------------------------- 1 | /*Write a method called printPowersOf2 that accepts a maximum number as an argument and prints each power of 2 from 20 (1) up 2 | to that maximum power, inclusive. For example, consider the following calls: 3 | 4 | 5 | printPowersOf2(3); 6 | printPowersOf2(10); 7 | These calls should produce the following output: 8 | 9 | 1 2 4 8 10 | 1 2 4 8 16 32 64 128 256 512 1024 11 | You may assume that the value passed to printPowersOf2 is 0 or greater. (The Math class may help you with this problem. 12 | If you use it, you may need to cast its results from double to int so that you don't see a .0 after each number in your output. 13 | Also, can you write this program without using the Math class?)*/ 14 | 15 | public static void printPowersOf2(int number) { 16 |     int multiply = 1; 17 |     for(int i = 0; i <= number; i++) { 18 |         System.out.print(multiply + " "); 19 |         multiply *= 2; 20 |     } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.8: quadratic.java: -------------------------------------------------------------------------------- 1 | /*Write a method called quadratic that solves quadratic equations and prints their roots. Recall that a quadratic equation is 2 | a polynomial equation in terms of a variable x of the form a x2 + b x + c = 0. 3 | 4 | Your method should accept the coefficients a, b, and c as parameters and should print the roots of the equation. You may 5 | assume that the equation has two real roots, though mathematically this is not always the case. 6 | 7 | Also, there should be two roots, one the result of the addition, the other, the result of the subtraction. Print the root 8 | resulting from the addition first.*/ 9 | public static void quadratic(int a, int b, int c) { 10 |     double root1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); 11 |     double root2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); 12 |      13 |     System.out.println("First root = " + root1); 14 |     System.out.println("Second root = " + root2); 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.8: Stewie2.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named Stewie2 that prints the following output. Use at least one static method besides main to remove redundancy. 2 | 3 | ////////////////////// 4 | || Victory is mine! || 5 | \\\\\\\\\\\\\\\\\\\\\\ 6 | || Victory is mine! || 7 | \\\\\\\\\\\\\\\\\\\\\\ 8 | || Victory is mine! || 9 | \\\\\\\\\\\\\\\\\\\\\\ 10 | || Victory is mine! || 11 | \\\\\\\\\\\\\\\\\\\\\\ 12 | || Victory is mine! || 13 | \\\\\\\\\\\\\\\\\\\\\\ 14 | 15 | */ 16 | 17 | public class Stewie2 { 18 |     public static void main(String[] args) { 19 |         victory(); 20 |     } 21 |     public static void victory() { 22 |         String top = "//////////////////////"; 23 |         String bottom = "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"; 24 |         String text = "|| Victory is mine! ||"; 25 |         String s = text + "\n" + bottom + "\n"; 26 |         System.out.print(top + "\n" + s + s + s + s + s); 27 |     } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.6: printRange.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printRange that accepts two integers as arguments and prints the sequence of numbers between the two arguments, 2 | separated by spaces. Print an increasing sequence if the first argument is smaller than the second; otherwise, print a decreasing 3 | sequence. If the two numbers are the same, that number should be printed by itself. Here are some sample calls to printRange: 4 | 5 | 6 | printRange(2, 7); 7 | printRange(19, 11); 8 | printRange(5, 5); 9 | The output produced should be the following: 10 | 11 | 2 3 4 5 6 7 12 | 19 18 17 16 15 14 13 12 11 13 | 5 14 | */ 15 | public static void printRange(int s, int f) { 16 | if(s > f) { 17 | for(int i = s; i >= f; i--) { 18 | System.out.print(i + " "); 19 | } 20 | } else if( s < f) { 21 | for(int i = s; i <= f; i++) { 22 | System.out.print(i + " "); 23 | } 24 | } else { 25 | System.out.println(s); 26 | } 27 |         System.out.println(); 28 | } 29 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.5: mode.java: -------------------------------------------------------------------------------- 1 | /*Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array 2 | has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value. 3 | 4 | For example, if the array passed contains the values {27, 15, 15, 11, 27}, your method should return 15. (Hint: You may wish 5 | to look at the Tally program from earlier in this chapter to get an idea of how to solve this problem.)*/ 6 | 7 | public static int mode(int[] array) { 8 | int[] spareArray = new int[101]; 9 | for (int i = 0; i < array.length; i++) { 10 | spareArray[array[i]]++; 11 | } 12 | int mode = 101; 13 | int count = 0; 14 | for (int i = 0; i < spareArray.length; i++) { 15 | if (spareArray[i] > count) { 16 | count = spareArray[i]; 17 | mode = i; 18 | } 19 | } 20 | 21 | return mode; 22 | } 23 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.9: parameterMysterySoda.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following program? 2 | 3 | 4 | public class MysterySoda { 5 | public static void main(String[] args) { 6 | String soda = "coke"; 7 | String pop = "pepsi"; 8 | String coke = "pop"; 9 | String pepsi = "soda"; 10 | String say = pop; 11 | carbonated(coke, soda, pop); 12 | carbonated(pop, pepsi, pepsi); 13 | carbonated("pop", pop, "koolaid"); 14 | carbonated(say, "say", pop); 15 | } 16 | ​ 17 | public static void carbonated(String coke, String soda, String pop) { 18 | System.out.println("say " + soda + " not " + pop + " or " + coke); 19 | } 20 | }*/ 21 | 22 | carbonated(coke, soda, pop); say coke not pepsi or pop 23 | carbonated(pop, pepsi, pepsi); say soda not soda or pepsi 24 | carbonated("pop", pop, "koolaid"); say pepsi not koolaid or pop 25 | carbonated(say, "say", pop); say say not pepsi or pepsi 26 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.28: Confusing3.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following program? You may wish to draw a structure diagram first. 2 | This is a slightly modified version of the previous problem, Confusing2. 3 | 4 | 5 | public class Confusing { 6 | public static void main(String[] args) { 7 | method2(); 8 | method1(); 9 | method3(); 10 | method2(); 11 | } 12 | 13 | public static void method2() { 14 | method1(); 15 | System.out.println("I am method 2."); 16 | } 17 | 18 | public static void method3() { 19 | method2(); 20 | System.out.println("I am method 3."); 21 | method1(); 22 | } 23 | 24 | public static void method1() { 25 | System.out.println("I am method 1."); 26 | } 27 | }*/ 28 | I am method 1. 29 | I am method 2. 30 | I am method 1. 31 | I am method 1. 32 | I am method 2. 33 | I am method 3. 34 | I am method 1. 35 | I am method 1. 36 | I am method 2. 37 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.16: SlashFigure.java: -------------------------------------------------------------------------------- 1 | /*Write a Java program in a class named SlashFigure that produces the following output. Use nested for loops to capture the structure of the figure. (If you previously solved Self-Check problems 34 and 35 in the book, you will have created a loop table that will be useful in solving this problem. Use it!) 2 | 3 | !!!!!!!!!!!!!!!!!!!!!! 4 | \\!!!!!!!!!!!!!!!!!!// 5 | \\\\!!!!!!!!!!!!!!//// 6 | \\\\\\!!!!!!!!!!////// 7 | \\\\\\\\!!!!!!//////// 8 | \\\\\\\\\\!!////////// 9 | 10 | */ 11 | 12 | public class SlashFigure { 13 | 14 | public static void main(String[] args) { 15 | for(int i = 1; i <= 6; i++) { 16 |             for(int j = 0; j < 2 * i - 2; j++) 17 |                 System.out.print("\\"); 18 |             for(int j = 0; j < -4 * i + 26; j++) 19 |                 System.out.print("!"); 20 |             for(int j = 0; j < 2 * i - 2; j++) 21 |                 System.out.print("/"); 22 |             System.out.println(); 23 | 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.27: Confusing2.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following program? You may wish to draw a structure diagram first. 2 | This is a slightly modified version of the previous problem, Confusing. 3 | 4 | 5 | public class Confusing { 6 | public static void main(String[] args) { 7 | method1(); 8 | method3(); 9 | method2(); 10 | method3(); 11 | } 12 | ​ 13 | public static void method2() { 14 | method1(); 15 | System.out.println("I am method 2."); 16 | } 17 | 18 | public static void method3() { 19 | method1(); 20 | method2(); 21 | System.out.println("I am method 3."); 22 | } 23 | public static void method1() { 24 | System.out.println("I am method 1."); 25 | } 26 | }*/ 27 | I am method 1. 28 | I am method 1. 29 | I am method 1. 30 | I am method 2. 31 | I am method 3. 32 | I am method 1. 33 | I am method 2. 34 | I am method 1. 35 | I am method 1. 36 | I am method 2. 37 | I am method 3. 38 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.9: evenSumMax.java: -------------------------------------------------------------------------------- 1 | /*Write a method named evenSum that prompts the user for many integers and print the total even sum and maximum of the even numbers. 2 | You may assume that the user types at least one non-negative even integer. 3 | 4 | how many integers? 4 5 | next integer? 2 6 | next integer? 9 7 | next integer? 18 8 | next integer? 4 9 | even sum = 24 10 | even max = 18 11 | */ 12 | public static void evenSum() { 13 | Scanner console = new Scanner(System.in); 14 | System.out.print("how many integers? "); 15 | int number = console.nextInt(); 16 | int evenSum = 0; 17 | int evenMax = 0; 18 | for(int i = 1; i <= number; i++) { 19 | System.out.print("next integer? "); 20 | int num = console.nextInt(); 21 | if(num % 2 == 0) { 22 | evenSum += num; 23 | } 24 | if(num % 2 == 0) { 25 | if(num > evenMax) { 26 | evenMax = num; 27 | } 28 | 29 | } 30 | } 31 | System.out.println("even sum = " + evenSum); 32 | System.out.println("even max = " + evenMax); 33 | } 34 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.23: Strange.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following program? You may wish to draw a structure diagram first. 2 | 3 | 4 | public class Strange { 5 | public static void main(String[] args) { 6 | first(); 7 | third(); 8 | second(); 9 | third(); 10 | } 11 | 12 | public static void first() { 13 | System.out.println("Inside first method."); 14 | } 15 | 16 | public static void second() { 17 | System.out.println("Inside second method."); 18 | first(); 19 | } 20 | 21 | public static void third() { 22 | System.out.println("Inside third method."); 23 | first(); 24 | second(); 25 | } 26 | }*/ 27 | Inside first method. 28 | Inside third method. 29 | Inside first method. 30 | Inside second method. 31 | Inside first method. 32 | Inside second method. 33 | Inside first method. 34 | Inside third method. 35 | Inside first method. 36 | Inside second method. 37 | Inside first method. 38 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.7: parameterMysteryWho.java: -------------------------------------------------------------------------------- 1 | /*Given the following program: 2 | 3 | 4 | public class MysteryWho { 5 | public static void main(String[] args) { 6 | String whom = "her"; 7 | String who = "him"; 8 | String it = "who"; 9 | String he = "it"; 10 | String she = "whom"; 11 | ​ 12 | sentence(he, she, it); 13 | sentence(she, he, who); 14 | sentence(who, she, who); 15 | sentence(it, "stu", "boo"); 16 | sentence(it, whom, who); 17 | } 18 | ​ 19 | public static void sentence(String she, String who, String whom) { 20 | System.out.println(who + " and " + whom + " like " + she); 21 | } 22 | }*/ 23 | Write the output of each of the following calls. 24 | 25 | sentence(he, she, it); whom and who like it 26 | sentence(she, he, who); it and him like whom 27 | sentence(who, she, who); whom and him like him 28 | sentence(it, "stu", "boo"); stu and boo like who 29 | sentence(it, whom, who); her and him like who 30 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.21: perfectNumbers.java: -------------------------------------------------------------------------------- 1 | /*A "perfect number" is a positive integer that is the sum of all its proper factors (that is, factors including 1 but not the number itself). 2 | The first two perfect numbers are 6 and 28, since 1+2+3=6 and 1+2+4+7+14=28. Write a static method perfectNumbers that takes an 3 | integer max as an argument and prints out all perfect numbers that are less than or equal to max. 4 | 5 | Here is the console output from a call to perfectNumbers(6): 6 | 7 | Perfect numbers up to 6: 6 8 | Here is the console output from a call to perfectNumbers(500): 9 | 10 | Perfect numbers up to 500: 6 28 496 11 | */ 12 | public static void perfectNumbers(int max) { 13 | String k = ""; 14 | int sum = 0; 15 | for(int i = 1; i <= max; i++) { 16 | for(int j = 1; j < i; j++)  17 | if(i % j == 0) { 18 | sum += j; 19 | } 20 | if(sum == i) { 21 |  k+= i + " "; 22 | } 23 |             sum = 0; 24 |         } 25 |     System.out.println("Perfect numbers up to " + max + ": " + k); 26 | } 27 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.3: printPowersOfN.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from 2 | base0 (1) up to that maximum power, inclusive. For example, consider the following calls: 3 | 4 | 5 | printPowersOfN(4, 3); 6 | printPowersOfN(5, 6); 7 | printPowersOfN(-2, 8); 8 | These calls should produce the following output: 9 | 10 | 1 4 16 64 11 | 1 5 25 125 625 3125 15625 12 | 1 -2 4 -8 16 -32 64 -128 256 13 | 14 | You may assume that the exponent passed to printPowersOfN has a value of 0 or greater. (The Math class may help you with this 15 | problem. If you use it, you may need to cast its results from double to int so that you don't see a .0 after each number in 16 | your output. Also, can you write this program without using the Math class?)*/ 17 | 18 | public static void printPowersOfN(int num1, int num2) { 19 |     int m = 1; 20 |     for(int i = 0; i <= num2; i++) { 21 |         System.out.print(m + " " ); 22 |         m *= num1; 23 |     } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.20: inputBirthday.java: -------------------------------------------------------------------------------- 1 | /*Write a method called inputBirthday that accepts a Scanner for the console as a parameter and prompts the user to enter 2 | a month, day, and year of birth, then prints the birthdate in a suitable format. Here is an example dialogue with the user: 3 | 4 | On what day of the month were you born? 8 5 | What is the name of the month in which you were born? May 6 | During what year were you born? 1981 7 | You were born on May 8, 1981. You're mighty old! 8 | 9 | */ 10 | public static void inputBirthday(Scanner console) { 11 |     System.out.print("On what day of the month were you born? "); 12 |     int day = console.nextInt(); 13 |     System.out.print("What is the name of the month in which you were born? "); 14 |     String monthName = console.next(); 15 |     System.out.print("During what year were you born? "); 16 |     int year = console.nextInt(); 17 |     System.out.print("You were born on " + monthName + " " + day + ", " + year + ". "); 18 |     System.out.println("You're mighty old!");    19 | } 20 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.6: parameterMysteryNumbers.java: -------------------------------------------------------------------------------- 1 | /*Given the following program: 2 | 3 | 4 | public class MysteryNumbers { 5 | public static void main(String[] args) { 6 | String one = "two"; 7 | String two = "three"; 8 | String three = "1"; 9 | int number = 20; 10 | ​ 11 | sentence(one, two, 3); 12 | sentence(two, three, 14); 13 | sentence(three, three, number + 1); 14 | sentence(three, two, 1); 15 | sentence("eight", three, number / 2); 16 | } 17 | ​ 18 | public static void sentence(String three, String one, int number) { 19 | System.out.println(one + " times " + three + " = " + (number * 2)); 20 | } 21 | }*/ 22 | Write the output of each of the following calls. 23 | 24 | 25 | sentence(one, two, 3); three times two = 6 26 | sentence(two, three, 14); 1 times three = 28 27 | sentence(three, three, number + 1); 1 times 1 = 42 28 | sentence(three, two, 1); three times 1 = 2 29 | sentence("eight", three, number / 2); 1 times eight = 20 30 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.10: printGPA.java: -------------------------------------------------------------------------------- 1 | /*Write a method named printGPA that calculates a student's grade point average. The user will type a line of input containing 2 | the student's name, then a number of scores, followed by that many integer scores. Here are two example dialogues: 3 | 4 | 5 | Enter a student record: Maria 5 72 91 84 89 78 6 | Maria's grade is 82.8 7 | Enter a student record: Jordan 4 86 71 62 90 8 | Jordan's grade is 77.25 9 | 10 | For example, Maria's grade is 82.8 because her average of (72 + 91 + 84 + 89 + 78) / 5 equals 82.8. Use a Scanner for user input.*/ 11 | 12 | public static void printGPA() { 13 | Scanner console = new Scanner(System.in); 14 | System.out.print("Enter a student record: "); 15 | String name = console.next(); 16 | int number = console.nextInt(); 17 | 18 | int sum = 0; 19 | for(int j = 1; j <= number; j++) { 20 | int points = console.nextInt(); 21 | sum += points; 22 | } 23 | double average = (double) sum / number; 24 | System.out.println(name + "'s grade is " + average); 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.2: range.java: -------------------------------------------------------------------------------- 1 | /*Write a static method named range that takes an array of integers as a parameter and returns the range of values contained in the 2 | array. The range of an array is defined to be one more than the difference between its largest and smallest element. For example, if 3 | the largest element in the array is 15 and the smallest is 4, the range is 12. If the largest and smallest values are the same, the range is 1. 4 | You may assume that the array contains at least one element (that its length is at least 1). You should not make any assumptions about the 5 | values of the particular elements in the array; they could be extremely large, very small, etc. You should not modify the contents 6 | of the array.*/ 7 | 8 | public static int range(int[] array) { 9 | int min = array[0]; 10 | int max = array[0]; 11 | for(int i = 0; i < array.length; i++) { 12 | if(array[i] < min) { 13 | min = array[i]; 14 | } 15 | if(array[i] > max) { 16 | max = array[i]; 17 | } 18 | } 19 | return Math.abs(min - max) + 1; 20 | } 21 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.25: Strange3.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following program? You may wish to draw a structure diagram first. 2 | This is a slightly modified version of the previous problem, Strange. 3 | 4 | public class Strange { 5 | public static void main(String[] args) { 6 | second(); 7 | first(); 8 | second(); 9 | third(); 10 | } 11 | 12 | public static void first() { 13 | System.out.println("Inside first method."); 14 | } 15 | 16 | public static void second() { 17 | System.out.println("Inside second method."); 18 | first(); 19 | } 20 | 21 | public static void third() { 22 | System.out.println("Inside third method."); 23 | first(); 24 | second(); 25 | } 26 | }*/ 27 | Inside second method. 28 | Inside first method. 29 | Inside first method. 30 | Inside second method. 31 | Inside first method. 32 | Inside third method. 33 | Inside first method. 34 | Inside second method. 35 | Inside first method. 36 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.13: colors.java: -------------------------------------------------------------------------------- 1 | /*Write a piece of code that reads a shorthand text description of a color and prints the longer equivalent. Acceptable color names 2 | are B for Blue, G for Green, and R for Red. If the user types something other than B, G, or R, the program should printan error 3 | message. Make your program case-insensitive so that the user can type an uppercase or lowercase letter. Here are two example executions: 4 | 5 | What color do you want? R 6 | You have chosen Red. 7 | What color do you want? Bork 8 | Unknown color: Bork 9 | */ 10 | Scanner console = new Scanner(System.in); 11 | System.out.print("What color do you want? "); 12 | String color = console.next(); 13 | if(color.equalsIgnoreCase("R")) { 14 |     System.out.println("You have chosen Red."); 15 | } else if(color.equalsIgnoreCase("B")) { 16 |     System.out.println("You have chosen Blue."); 17 | } else if(color.equalsIgnoreCase("G")) { 18 |     System.out.println("You have chosen Green."); 19 | } else { 20 |     System.out.println("Unknown color: " + color); 21 | } 22 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.10: Stairs.java: -------------------------------------------------------------------------------- 1 | /*Finish the given program called Stairs that uses the DrawingPanel to draw the figure shown below. The window is 110 x 110 px in 2 | size. The first stair's top-left corner is at position (5, 5). The first stair is 10 x 10 pixels in size. Each stair is 10 pixels 3 | wider than the one above it. (If you're having trouble matching the output, make a table with the (x, y) coordinates and 4 | (width x height) sizes of the first five stairs. Note which values change and which ones stay the same.) 5 | 6 | (You don't need to include any import statements at the top of your program.) (The next exercise is a modified version of this 7 | program, so you can use the code you write here as a starting point for that exercise.)*/ 8 | 9 | public class Stairs { 10 |     public static void main(String[] args) { 11 |         DrawingPanel panel = new DrawingPanel(110, 110); 12 |         Graphics g = panel.getGraphics(); 13 |         for (int i = 1; i <= 10; i++) { 14 |             g.drawRect(5, 10 * i - 5, 10 * i, 10); 15 |         } 16 |     } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.22: DollarFigure.java: -------------------------------------------------------------------------------- 1 | /*Write a Java program called DollarFigure that produces the following output. Use nested for loops to capture the structure of the figure. 2 | 3 | $$$$$$$**************$$$$$$$ 4 | **$$$$$$************$$$$$$** 5 | ****$$$$$**********$$$$$**** 6 | ******$$$$********$$$$****** 7 | ********$$$******$$$******** 8 | **********$$****$$********** 9 | ************$**$************ 10 | 11 | */ 12 | public class DollarFigure { 13 | 14 | public static void main(String[] args) { 15 | for(int i = 1; i <= 7; i++) { 16 |             for(int j = 0; j < 2 * i - 2; j++) 17 |                 System.out.print("*"); 18 |             for(int j = 0; j < -i + 8; j++) 19 |                 System.out.print("$"); 20 |             for(int j = 0; j < -2 * i + 16; j++) 21 |                 System.out.print("*"); 22 |             for(int j = 0; j < -i + 8; j++) 23 |                 System.out.print("$"); 24 |             for(int j = 0; j < 2 * i - 2; j++) 25 |                 System.out.print("*"); 26 |             System.out.println(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.9: Squares3.java: -------------------------------------------------------------------------------- 1 | /*Modify your Squares2 program from the previous exercise into a new class Squares3 that draws the following figures. 2 | (Go back to that problem and copy/paste your code here as a starting point.) Parameterize your program so that the figures have 3 | the sizes shown below. The top-right figure has size 50, and the bottom-right figure has size 180.*/ 4 | 5 | public class Squares3 { 6 |     public static void main(String[] args) { 7 |         DrawingPanel panel = new DrawingPanel(); 8 |         panel.setBackground(Color.CYAN); 9 |         panel.setSize(400, 300); 10 |         Graphics g = panel.getGraphics(); 11 |         drawingFigure(g, 50, 50, 100); 12 | drawingFigure(g, 250, 10, 50); 13 | drawingFigure(g, 180, 115, 180); 14 |     } 15 |         public static void drawingFigure(Graphics g, int x, int y, int j) { 16 |             g.setColor(Color.RED); 17 | for(int i = 0; i < 6; i++) { 18 | g.drawRect(x, y, i * (j / 5), i * (j / 5)); 19 | } 20 | g.setColor(Color.BLACK); 21 | g.drawLine(x, y, x + j, y + j); 22 |     } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.10: Oops2-errors.java: -------------------------------------------------------------------------------- 1 | /*The following program contains 9 errors. Correct the errors and submit a working version of the program. The corrected 2 | version of the program should produce the following output: 3 | 4 | x is 0 5 | x is now 15 6 | x and y are 15 and 16 7 | 8 | public class Oops2 { 9 | public static void main(String[] args) { 10 | int x; 11 | System.out.println("x is " x); 12 | 13 | int x = 15.2; // set x to 15.2 14 | System.out.println("x is now + x"); 15 | 16 | int y; // set y to 1 more than x 17 | y = int x + 1; 18 | System.out.println("x and y are " + x + and + y); 19 | } 20 | }*/ 21 | 22 | public class Oops2 { 23 |     public static void main(String[] args) { 24 |         int x = 0; 25 |         System.out.println("x is " + x); 26 | 27 |         x = 15;   // set x to 15 28 |         System.out.println("x is now " + x); 29 | 30 |         // set y to 1 more than x 31 |         int y = x + 1; 32 |         System.out.println("x and y are " + x + " and " + y); 33 |     } 34 | } 35 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.12: printTriangleType.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printTriangleType that accepts three integer arguments representing the lengths of the sides of a triangle 2 | and prints what type of triangle it is. The three types are equilateral, isosceles, and scalene. An equilateral triangle has 3 | all three sides the same length, an isosceles triangle has two sides the same length, and a scalene triangle has three sides 4 | of different lengths. Here are some example calls to printTriangleType: 5 | 6 | printTriangleType(5, 7, 7); 7 | printTriangleType(6, 6, 6); 8 | printTriangleType(5, 7, 8); 9 | printTriangleType(12, 18, 12); 10 | The output produced should be the following: 11 | 12 | isosceles 13 | equilateral 14 | scalene 15 | isosceles 16 | */ 17 | public static void printTriangleType(int a, int b, int c) { 18 | if(a != b && b == c || a != c && a == b || c != b && a == c) { 19 | System.out.println("isosceles"); 20 | } else if(a == b && b == c && c == a) { 21 | System.out.println("equilateral"); 22 | } else { 23 | System.out.println("scalene"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.5: ShowDesign.java: -------------------------------------------------------------------------------- 1 | /*Write a complete program in a class named ShowDesign that uses the DrawingPanel to draw the following figure: 2 | 3 | The window is 200 pixels wide and 200 pixels tall. The background is white and the foreground is black. There are 20 pixels 4 | between each of the four rectangles, and the rectangles are concentric (their centers are at the same point). Use a loop to 5 | draw the repeated rectangles. 6 | 7 | (You don't need to include any import statements at the top of your program.) (The next exercise is a modified version of this 8 | program, so you can use the code you write here as a starting point for that exercise.)*/ 9 | 10 | public class ShowDesign { 11 |     public static void main(String[] args) { 12 |         DrawingPanel panel = new DrawingPanel(200, 200); 13 |         Graphics g = panel.getGraphics(); 14 |         g.setColor(Color.WHITE); 15 | g.fillRect(5, 5, 190, 190); 16 | g.setColor(Color.BLACK); 17 | for(int i = 1; i < 5; i++) { 18 |             g.drawRect(i * 20, i * 20, 200 - (i * 40), 200 - (i * 40)); 19 |         } 20 |     } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.24: Strange2.java: -------------------------------------------------------------------------------- 1 | /*What is the output produced from the following program? You may wish to draw a structure diagram first. This is 2 | a slightly modified version of the previous problem, Strange. 3 | 4 | public class Strange { 5 | public static void main(String[] args) { 6 | first(); 7 | third(); 8 | second(); 9 | third(); 10 | } 11 | 12 | public static void first() { 13 | System.out.println("Inside first method."); 14 | } 15 | 16 | public static void second() { 17 | System.out.println("Inside second method."); 18 | first(); 19 | } 20 | 21 | public static void third() { 22 | first(); 23 | second(); 24 | System.out.println("Inside third method."); 25 | } 26 | }*/ 27 | Inside first method. 28 | Inside first method. 29 | Inside second method. 30 | Inside first method. 31 | Inside third method. 32 | Inside second method. 33 | Inside first method. 34 | Inside first method. 35 | Inside second method. 36 | Inside first method. 37 | Inside third method. 38 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.14: parameterMysteryReturn.java: -------------------------------------------------------------------------------- 1 | /*Given the following program: 2 | 3 | 4 | public class MysteryReturn { 5 | public static void main(String[] args) { 6 | int x = 1; 7 | int y = 2; 8 | int z = 3; 9 | 10 | z = mystery(x, z, y); // Statement 1 11 | System.out.println(x + " " + y + " " + z); // Statement 2 12 | x = mystery(z, z, x); // Statement 3 13 | System.out.println(x + " " + y + " " + z); // Statement 4 14 | y = mystery(y, y, z); // Statement 5 15 | System.out.println(x + " " + y + " " + z); // Statement 6 16 | } 17 | ​ 18 | public static int mystery(int z, int x, int y) { 19 | z--; 20 | x = 2 * y + z; 21 | y = x - 1; 22 | System.out.println(y + " " + z); 23 | return x; 24 | } 25 | } 26 | Write the output of each statement.*/ 27 | 28 | 29 | Statement 1 3 0 30 | Statement 2 1 2 4 31 | Statement 3 4 3 32 | Statement 4 5 2 4 33 | Statement 5 8 1 34 | Statement 6 5 9 4 35 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.22: loopTable.java: -------------------------------------------------------------------------------- 1 | /*Assume that you have a variable called count that will take on the values 1, 2, 3, 4, and so on. You are going to formulate 2 | expressions in terms of count that will yield different sequences. The first row is filled in for you as an example. 3 | Fill in the solution boxes below, indicating an expression that will generate each sequence. Your answers should be 4 | in the form 'coefficient * count + constant' in that order, or the solution checking may not be accurate. 5 | 6 | Problem # count value Sequence Expression 7 | 1, 2, 3, 4, 5, 6, ... 2, 4, 6, 8, 10, 12, ... 2 * count*/ 8 | 1 1, 2, 3, 4, 5, 6, ... 4, 19, 34, 49, 64, 79, ... 15 * count - 11 9 | 2 1, 2, 3, 4, 5, 6, ... 30, 20, 10, 0, -10, -20, ... -10 * count + 40 10 | 3 1, 2, 3, 4, 5, 6, ... -7, -3, 1, 5, 9, 13, ... 4 * count - 11 11 | 4 1, 2, 3, 4, 5, 6, ... 97, 94, 91, 88, 85, 82, ... -3 * count + 100 12 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.5: expressions3.java: -------------------------------------------------------------------------------- 1 | /*Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of 2 | the appropriate type (such as including a .0 at the end of a double or quotes around a String).*/ 3 | 4 | 2 + 2 + 3 + 4 --------> 11 5 | "2 + 2 " + 3 + 4 --------> "2 + 2 34" 6 | 2 + " 2 + 3 " + 4 --------> "2 2 + 3 4" 7 | 3 + 4 + " 2 + 2" --------> "7 2 + 2" 8 | "2 + 2 " + (3 + 4) --------> "2 + 2 7" 9 | "(2 + 2) " + (3 + 4) --------> "(2 + 2) 7" 10 | "hello 34 " + 2 * 4 --------> "hello 34 8" 11 | 2 + "(int) 2.0" + 2 * 2 + 2 --------> "2(int) 2.042" 12 | 4 + 1 + 9 + "." + (-3 + 10) + 11 / 3 --------> "14.73" 13 | 8 + 6 * -2 + 4 + "0" + (2 + 5) --------> "007" 14 | 1 + 1 + "8 - 2" + (8 - 2) + 1 + 1 --------> "28 - 2611" 15 | 5 + 2 + "(1 + 1)" + 4 + 2 * 3 --------> "7(1 + 1)46" 16 | "1" + 2 + 3 + "4" + 5 * 6 + "7" + (8 + 9) --------> "123430717" 17 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.6: stdev.java: -------------------------------------------------------------------------------- 1 | /*Write a method called stdev that returns the standard deviation of an array of integers. Standard deviation is computed by taking 2 | the square root of the sum of the squares of the differences between each element and the mean, divided by one less than the number 3 | of elements. (It's just that simple!). 4 | For example, if the array passed contains the values {1, -2, 4, -4, 9, -6, 16, -8, 25, -10}, your method should return approximately 5 | 11.237. You may assume that the array passed is non-null and contains at least two values, because the standard deviation is undefined otherwise. 6 | 7 | (Note: you might fail the last two tests because of rounding, but as long as it's close, then your algorithm is probably correct.)*/ 8 | 9 | public static double stdev(int[] array) { 10 | double sum = 0; 11 | for(int i = 0; i < array.length; i++) { 12 | sum+=array[i]; 13 | } 14 | double average = sum / array.length; 15 | double x = 0; 16 | for(int i = 0; i < array.length; i++) { 17 | x+=(array[i] - average ) * ( array[i] - average); 18 | } 19 | return Math.sqrt(x / (array.length - 1)); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.8: smallestLargest.java: -------------------------------------------------------------------------------- 1 | /*Write a method named smallestLargest that asks the user to enter numbers, then prints the smallest and largest of all the numbers 2 | typed in by the user. You may assume the user enters a valid number greater than 0 for the number of numbers to read. Here is an 3 | example dialogue: 4 | 5 | How many numbers do you want to enter? 4 6 | Number 1: 5 7 | Number 2: 11 8 | Number 3: -2 9 | Number 4: 3 10 | Smallest = -2 11 | Largest = 11 12 | */ 13 |    public static void smallestLargest() { 14 | Scanner console = new Scanner(System.in); 15 | System.out.print("How many numbers do you want to enter? "); 16 | int numbers = console.nextInt(); 17 | int smalest = Integer.MAX_VALUE; 18 |     int largest = Integer.MIN_VALUE; 19 | 20 | for(int i = 1; i <= numbers; i++) { 21 | System.out.print("Number " + i + ": "); 22 | int num = console.nextInt(); 23 | if(num < smalest) {  24 | smalest = num; 25 | } 26 | if(num > largest) { 27 | largest = num; 28 | } 29 | } 30 | System.out.println("Smallest = " + smalest); 31 | System.out.println("Largest = " + largest); 32 | } 33 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.5: printGrid.java: -------------------------------------------------------------------------------- 1 | /*Write a method named printGrid that accepts two integer parameters rows and cols. The output is a comma-separated grid of 2 | numbers where the first parameter (rows) represents the number of rows of the grid and the second parameter (cols) represents 3 | the number of columns. The numbers count up from 1 to (rows x cols). The output are displayed in column-major order, meaning 4 | that the numbers shown increase sequentially down each column and wrap to the top of the next column to the right once the 5 | bottom of the current column is reached. Assume that rows and cols are greater than 0. 6 | 7 | Here are some example calls to your method and their expected results:*/ 8 | 9 | public static void printGrid(int rows, int cols) { 10 |     int a = 0; 11 |     for(int i = 1; i <= rows; i++) { 12 |         for(int j = 1; j <= cols; j++) { 13 |             a = i + rows * (j - 1); 14 |             System.out.print(a); 15 |             a++; 16 |             if(a <= (rows * cols) - rows + 1) { 17 |                 System.out.print(", "); 18 |             } 19 |         } 20 |         System.out.println(); 21 |     } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.3: expressions1.java: -------------------------------------------------------------------------------- 1 | /*Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of 2 | the appropriate type (such as including a .0 at the end of a double).*/ 3 | 4 | 2 + 3 * 4 - 6 --------> 8 5 | 14 / 7 * 2 + 30 / 5 + 1 --------> 11 6 | (12 + 3) / 4 * 2 --------> 6 7 | (238 % 10 + 3) % 7 --------> 4 8 | (18 - 7) * (43 % 10) --------> 33 9 | 2 + 19 % 5 - (11 * (5 / 2)) --------> -16 10 | 813 % 100 / 3 + 2.4 --------> 6.4 11 | 26 % 10 % 4 * 3 --------> 6 12 | 22 + 4 * 2 --------> 30 13 | 23 % 8 % 3 --------> 1 14 | 12 - 2 - 3 --------> 7 15 | 6/2 + 7/3 --------> 5 16 | 6 * 7 % 4 --------> 2 17 | 3 * 4 + 2 * 3 --------> 18 18 | 177 % 100 % 10 / 2 --------> 3 19 | 89 % (5 + 5) % 5 --------> 4 20 | 392 / 10 % 10 / 2 --------> 4 21 | 8 * 2 - 7 / 4 --------> 15 22 | 37 % 20 % 3 * 4 --------> 8 23 | 17 % 10 / 4 --------> 1 24 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.8: parameterMysteryTouch.java: -------------------------------------------------------------------------------- 1 | /*What output is produced by the following program? 2 | 3 | 4 | public class MysteryTouch { 5 | public static void main(String[] args) { 6 | String head = "shoulders"; 7 | String knees = "toes"; 8 | String elbow = "head"; 9 | String eye = "eyes and ears"; 10 | String ear = "eye"; 11 | ​ 12 | touch(ear, elbow); 13 | touch(elbow, ear); 14 | touch(head, "elbow"); 15 | touch(eye, eye); 16 | touch(knees, "Toes"); 17 | touch(head, "knees " + knees); 18 | } 19 | 20 | public static void touch(String elbow, String ear) { 21 | System.out.println("touch your " + elbow + " to your " + ear); 22 | } 23 | }*/ 24 | 25 | touch(ear, elbow); touch your eye to your head 26 | touch(elbow, ear); touch your head to your eye 27 | touch(head, "elbow"); touch your shoulders to your elbow 28 | touch(eye, eye); touch your eyes and ears to your eyes and ears 29 | touch(knees, "Toes"); touch your toes to your Toes 30 | touch(head, "knees " + knees); touch your shoulders to your knees toes 31 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.15: getGrade.java: -------------------------------------------------------------------------------- 1 | /*Write a method called getGrade that accepts an integer representing a student's grade in a course and returns that student's 2 | numerical course grade. The grade can be between 0.0 (failing) and 4.0 (perfect). Assume that scores are in the range of 0 to 100 3 | and that grades are based on the following scale: 4 | 5 | Score Grade 6 | <60 0.0 7 | 60-62 0.7 8 | 63 0.8 9 | 64 0.9 10 | 65 1.0 11 | ... 12 | 92 3.7 13 | 93 3.8 14 | 94 3.9 15 | >=95 4.0 16 | 17 | For an added challenge, make your method throw an IllegalArgumentException if the user passes a grade lower than 0 or higher than 100.*/ 18 | 19 | public static double getGrade(int point) { 20 | if(point < 0 || point > 100) { 21 | throw new IllegalArgumentException(); 22 | 23 | } else if(point < 60) { 24 | return 0.0; 25 | } else if(point >= 60 && point < 62) { 26 | return 0.7; 27 | } else if(point >= 63 && point < 95) { 28 | double p = .0; 29 | p+= .8 + (point - 63) * .1; 30 | return p; 31 | } else if(point >= 95 && point <= 100) { 32 | return 4.0; 33 | } else { 34 | return 0; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.3: season.java: -------------------------------------------------------------------------------- 1 | /*Write a method named season that takes two integers as parameters representing a month and day and that returns a String indicating 2 | the season for that month and day. Assume that months are specified as an integer between 1 and 12 (1 for January, 2 for February, 3 | and so on) and that the day of the month is a number between 1 and 31. 4 | 5 | If the date falls between 12/16 and 3/15, you should return "Winter". If the date falls between 3/16 and 6/15, you should return 6 | "Spring". If the date falls between 6/16 and 9/15, you should return "Summer". And if the date falls between 9/16 and 12/15, 7 | you should return "Fall".*/ 8 | 9 | public static String season(int month, int day) { 10 | if(month < 3 || month == 3 && day <= 15 || (month == 12 && day >= 16)) { 11 | return "Winter"; 12 | } else if ((month < 6 && month > 3) || (month == 3 && day >= 16) || 13 | (month == 6 && day <= 15)) { 14 | return "Spring"; 15 | } else if((month > 6 && month < 9) || (month == 6 && day >= 16) || 16 | (month == 9 && day <= 15)) { 17 | return "Summer"; 18 | } else { 19 | return "Fall"; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.4: Face2.java: -------------------------------------------------------------------------------- 1 | /*Modify your Face program from the previous exercise into a new class Face2 to draw the new output shown below. The window size 2 | should be changed to 520 x 180 pixels, and the faces' top-left corners are at (10, 30), (110, 30), (210, 30), (310, 30), and (410, 30). Draw the figures using a loop to avoid redundancy. 3 | (You don't need to include any import statements at the top of your program.)*/ 4 | 5 | public class Face2 { 6 |     public static void main(String[] args) { 7 |         DrawingPanel panel = new DrawingPanel(520, 180); 8 |         Graphics g = panel.getGraphics(); 9 |         for(int i = 0; i < 5; i++) { 10 |             drawingFace(g, 10 + (i * 100), 30); 11 |         } 12 |     } 13 |         public static void drawingFace(Graphics g, int x, int y) { 14 |         g.setColor(Color.BLACK); 15 |         g.drawOval(x, y, 100, 100);   // face outline 16 | 17 |         g.setColor(Color.BLUE); 18 |         g.fillOval(x + 20, y + 30, 20, 20);     // eyes 19 |         g.fillOval(x + 60, y + 30, 20, 20); 20 | 21 |         g.setColor(Color.RED);          // mouth 22 |         g.drawLine(x + 30, y + 70, x + 70, y + 70); 23 |     } 24 | } 25 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.8: Squares2.java: -------------------------------------------------------------------------------- 1 | /*Modify your Squares program from the previous exercise into a new class Squares2 that draws the following figures. 2 | (Go back to that problem and copy/paste your code here as a starting point.) 3 | 4 | The drawing panel is now 400 by 300 pixels in size. The first figure is at the same position, (50,50). The other figures are at 5 | positions (250, 10) and (180, 115), respectively. Use one or more parameterized static methods to reduce the redundancy of your solution*/ 6 | 7 | public class Squares2 { 8 |     public static void main(String[] args) { 9 |         DrawingPanel panel = new DrawingPanel(); 10 |         panel.setBackground(Color.CYAN); 11 |         panel.setSize(400, 300); 12 |         Graphics g = panel.getGraphics(); 13 |         drawingFigure(g, 50, 50); 14 | drawingFigure(g, 250, 10); 15 | drawingFigure(g, 180, 115); 16 |     } 17 |         public static void drawingFigure(Graphics g, int x, int y) { 18 |             g.setColor(Color.RED); 19 | for(int i = 0; i < 6; i++) { 20 | g.drawRect(x, y, i * 20, i * 20); 21 | } 22 | g.setColor(Color.BLACK); 23 | g.drawLine(x, y, x + 100, y + 100); 24 |     } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Exercise 3.4: printSquare.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printSquare that takes in two integer parameters, a min and a max, and prints the numbers in the range 2 | from min to max inclusive in a square pattern. The square pattern is easier to understand by example than by explanation, so 3 | take a look at the sample method calls and their resulting console output in the table below. 4 | 5 | Each line of the square consists of a circular sequence of increasing integers between min and max. Each line prints a different 6 | permutation of this sequence. The first line begins with min, the second line begins with min + 1, and so on. When the sequence 7 | in any line reaches max, it wraps around back to min. 8 | 9 | You may assume the caller of the method will pass a min and a max parameter such that min is less than or equal to max.*/ 10 | 11 | public static void printSquare(int min, int max) { 12 |     for(int i = min; i <= max; i++) { 13 |         for(int j = i; j <= max; j++) { 14 |             System.out.print(j); 15 |         } 16 |         for(int k = 0; k < i - min; k++) { 17 |             System.out.print(min + k); 18 |         } 19 |         System.out.println(); 20 |     } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 3- Parameters and Objects/Self-Check 3.15: mathExpressions2.java: -------------------------------------------------------------------------------- 1 | /*Write the result of each expression. Assume that each expression follows the ones before it, so that the code on a previous 2 | line affects what would happen on the next line. Note that a variable's value changes only if you reassign it using 3 | the = operator. (Make sure to write a value of the proper type, such as 12.0 rather than 12 for a double.) 4 | 5 | 6 | double grade = 2.7; 7 | Math.round(grade); // a) grade = 8 | grade = Math.round(grade); // b) grade = 9 | ​ 10 | double min = Math.min(grade, Math.floor(2.9)); // c) min = 11 | ​ 12 | double x = Math.pow(2, 4); // d) x = 13 | x = Math.sqrt(64); // e) x = 14 | ​ 15 | int count = 25; 16 | Math.sqrt(count); // f) count = 17 | count = (int) Math.sqrt(count); // g) count = 18 | ​ 19 | int a = Math.abs(Math.min(-1, -3)); // h) a = 20 | */ 21 | 22 | a) grade = 2.7 23 | b) grade = 3.0 24 | c) min = 2.0 25 | d) x = 16.0 26 | e) x = 8.0 27 | f) count = 25 28 | g) count = 5 29 | h) a = 3 30 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.6: ShowDesign2.java: -------------------------------------------------------------------------------- 1 | /*Modify your ShowDesign class from the previous exercise into a new class ShowDesign2 that has a method named showDesign that 2 | accepts parameters for the window width and height and displays the rectangles at the appropriate sizes. For example, if your 3 | showDesign method was called with values of 300 and 100, the window would look like the following figure. 4 | 5 | (You don't need to include any import statements at the top of your program.)*/ 6 | 7 | public class ShowDesign2 { 8 |     public static void main(String[] args) { 9 |         DrawingPanel panel = new DrawingPanel(300, 100); 10 |         Graphics g = panel.getGraphics(); 11 |         showDesign(g, 300, 100); 12 |     } 13 |         public static void showDesign(Graphics g, int x, int y) { 14 |             g.setColor(Color.WHITE); 15 |     g.fillRect(0, 0, x, y); 16 | g.setColor(Color.BLACK); 17 |     for(int i = 1; i < 5; i++) { 18 |      int rectWidth = x - (x / 5) * i; 19 |     int rectHeight = y - (y / 5) * i; 20 |     int rectX = x / 10 * i; 21 |     int rectY = y / 10 * i; 22 |     g.drawRect(rectX, rectY, rectWidth, rectHeight); 23 |         } 24 |     } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.28: quadraticPreconditions.java: -------------------------------------------------------------------------------- 1 | /*Exercise 3.8 asked you to write a method called quadratic that solves quadratic equations and prints their roots. 2 | Recall that a quadratic equation is a polynomial equation in terms of a variable x of the form a x2 + b x + c = 0. 3 | But for some values of a, b, and c, the formula does not find any valid roots. Under what conditions would this formula fail? 4 | Modify the quadratic method so that it will reject invalid values of a, b, or c by throwing an IllegalArgumentException. 5 | (You may want to go back and complete the exercise in the previous chapter first.)*/ 6 | 7 | public static void quadratic(int a, int b, int c) { 8 |         double determinant = b * b - 4 * a * c; 9 |     if (a == 0) { 10 |         throw new IllegalArgumentException( "Invalid a value of 0"); 11 |     } 12 |     if (determinant < 0) { 13 |         throw new IllegalArgumentException( "Invalid determinant"); 14 |     } 15 |     double r1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); 16 |     double r2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); 17 |      18 |     System.out.println("First root = " + r1); 19 |     System.out.println("Second root = " + r2); 20 | } 21 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.13: Football.java: -------------------------------------------------------------------------------- 1 | /*Using the DrawingPanel class, write a Java class named Football that produces the following figure: 2 | Though the figure looks to contain curves, it is made entirely of straight lines. The window is 250 x 250 pixels in size, 3 | and there is an outer rectangle from (10, 30) to (210, 230). A set of black lines are drawn around the edges every 10 pixels. 4 | For example, along the top-left, there is a line from (10, 220) to (20, 30), a line from (10, 210) to (30, 30), a line from 5 | (10, 200) to (40, 30), ... and so on. 6 | Along the bottom-right, there is a line from (20, 230) to (210, 220), a line from (30, 230) to (210, 210), and so on.*/ 7 | 8 | public class Football { 9 |     public static void main(String[] args) { 10 |         DrawingPanel panel = new DrawingPanel(250, 250); 11 |         Graphics g = panel.getGraphics(); 12 |         g.setColor(Color.black); 13 | g.drawRect(10, 30, 200, 200); 14 | for(int i = 0; i < 20; i++) { 15 |             int x1 = 10; 16 | int y1 = 220 - 10 * i; 17 | int x2 = 20 + 10 * i; 18 | int y2 = 30; 19 |      g.drawLine(x1, y1, x2, y2); 20 |      g.drawLine(x2, 230, 210, y1); 21 |         } 22 |     } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.19: quadrant.java: -------------------------------------------------------------------------------- 1 | /*Write a static method called quadrant that takes as parameters a pair of real numbers representing an (x, y) point and that returns 2 | the quadrant number for that point. Recall that quadrants are numbered as integers from 1 to 4 with the upper-right quadrant numbered 3 | 1 and the subsequent quadrants numbered in a counter-clockwise fashion: 4 | 5 | Notice that the quadrant is determined by whether the x and y coordinates are positive or negative numbers. If a point falls on 6 | the x-axis or the y-axis, then the method should return 0. Below are sample calls on the method. 7 | 8 | Call Value Returned 9 | quadrant(12.4, 17.8) 1 10 | quadrant(-2.3, 3.5) 2 11 | quadrant(-15.2, -3.1) 3 12 | quadrant(4.5, -42.0) 4 13 | quadrant(0.0, 3.14) 0 14 | 15 | */ 16 | public static int quadrant(double x, double y) { 17 | if(x > 0 && y > 0) { 18 | return 1; 19 | } 20 | if(x < 0 && y > 0) { 21 | return 2; 22 | } 23 | if(x < 0 && y < 0) { 24 | return 3; 25 | } 26 | if(x > 0 && y < 0) { 27 | return 4; 28 | } else { 29 | return 0; 30 | } 31 | 32 | } 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Self-Check 2.4: expressions2.java: -------------------------------------------------------------------------------- 1 | /*Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of 2 | the appropriate type (such as including a .0 at the end of a double).*/ 3 | 4 | 5 | 4.0 / 2 * 9 / 2 -------> 9.0 6 | 2.5 * 2 + 8 / 5.0 + 10 / 3 -------> 9.6 7 | 12 / 7 * 4.4 * 2 / 4 -------> 2.2 8 | 4 * 3 / 8 + 2.5 * 2 -------> 6.0 9 | (5 * 7.0 / 2 - 2.5) / 5 * 2 -------> 6.0 10 | 41 % 7 * 3 / 5 + 5 / 2 * 2.5 -------> 8.0 11 | 10.0 / 2/4 -------> 1.25 12 | 8 / 5 + 13 / 2 / 3.0 -------> 3.0 13 | (2.5 + 3.5) / 2 -------> 3.0 14 | 9 / 4 * 2.0 - 5/4 -------> 3.0 15 | 9 / 2.0 + 7 / 3 - 3.0 / 2 -------> 5.0 16 | 813 % 100 / 3 + 2.4 -------> 6.4 17 | 27 / 2 / 2.0 * (4.3 + 1.7) - 8 / 3 -------> 37.0 18 | 53 / 5 / (0.6 + 1.4) / 2 + 13 / 2 -------> 8.5 19 | 2 * 3 / 4 * 2 / 4.0 + 4.5 - 1 -------> 4.0 20 | 89 % 10 / 4 * 2.0 / 5 + (1.5 + 1.0 / 2) * 2 ------->4.8 21 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.13: StarFigures.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named StarFigures that generates the following output. 2 | Use static methods to show structure and eliminate redundancy in your solution. 3 | 4 | ***** 5 | ***** 6 | * * 7 | * 8 | * * 9 | 10 | ***** 11 | ***** 12 | * * 13 | * 14 | * * 15 | ***** 16 | ***** 17 | 18 | * 19 | * 20 | * 21 | ***** 22 | ***** 23 | * * 24 | * 25 | * * 26 | */ 27 | 28 | public class StarFigures { 29 |     public static void main(String[] args) { 30 |         stars(); 31 |         second(); 32 |         System.out.println(); 33 |         stars(); 34 |         second(); 35 |         stars(); 36 |         last(); 37 |     } 38 |     public static void stars() { 39 |         System.out.println("*****"); 40 |         System.out.println("*****"); 41 |     } 42 |     public static void second() { 43 |         System.out.println(" * *"); 44 |         System.out.println("  *"); 45 |         System.out.println(" * *"); 46 |     } 47 |     public static void last() { 48 |         System.out.println(); 49 |         System.out.println("  *"); 50 |         System.out.println("  *"); 51 |         System.out.println("  *"); 52 |         stars(); 53 |         second(); 54 |     } 55 | } 56 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.15: EggStop.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named EggStop that generates the following output. 2 | Use static methods to show structure and eliminate redundancy in your solution. 3 | 4 | ______ 5 | / \ 6 | / \ 7 | \ / 8 | \______/ 9 | 10 | ______ 11 | / \ 12 | / \ 13 | \ / 14 | \______/ 15 | +--------+ 16 | 17 | ______ 18 | / \ 19 | / \ 20 | | STOP | 21 | \ / 22 | \______/ 23 | +--------+ 24 | 25 | */ 26 | 27 | public class EggStop { 28 | 29 | public static void main(String[] args) { 30 | combine(); 31 | topEgg(); 32 | System.out.println("|  STOP  |"); 33 | bottomEgg(); 34 | line(); 35 | } 36 | public static void topEgg() { 37 | System.out.println("  ______ "); 38 | System.out.println(" /      \\"); 39 | System.out.println("/        \\"); 40 | } 41 | public static void bottomEgg() { 42 | System.out.println("\\        /"); 43 | System.out.println(" \\______/"); 44 | } 45 | public static void line() { 46 | System.out.println("+--------+"); 47 |         System.out.println(); 48 | } 49 | public static void combine() { 50 | topEgg(); 51 | bottomEgg(); 52 | System.out.println(); 53 | topEgg(); 54 | bottomEgg(); 55 | line(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.21: StarFigure2.java: -------------------------------------------------------------------------------- 1 | /*Modify your StarFigure code from the previous problem to use a constant for the size. The outputs below use a constant size of 3 (left) and 6 (right): 2 | 3 | size 3 4 | ////////\\\\\\\\ 5 | ////********\\\\ 6 | **************** 7 | 8 | size 6 9 | ////////////////////\\\\\\\\\\\\\\\\\\\\ 10 | ////////////////********\\\\\\\\\\\\\\\\ 11 | ////////////****************\\\\\\\\\\\\ 12 | ////////************************\\\\\\\\ 13 | ////********************************\\\\ 14 | **************************************** 15 | 16 | (You must solve this problem using only ONE public static final constant, not multiple constants; and its value must be used 17 | in the way described in this problem.)*/ 18 | 19 | public class StarFigure2 { 20 |     public static final int R = 7; 21 |      22 | public static void main(String[] args) { 23 | for (int i = 1; i <= R; i++) { 24 |             for (int j = 1; j <= (4*R) - 4 * i; j++) { 25 |                 System.out.print("/"); 26 |              27 | } 28 | for (int j = 1; j <= 8 * i - 8; j++) { 29 |             System.out.print("*"); 30 | } 31 | for (int j = 1; j <= (4*R) - 4 * i; j++) { 32 |             System.out.print("\\"); 33 | } 34 | System.out.println(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Self-Check 1.32: Messy.java: -------------------------------------------------------------------------------- 1 | /*The following program is legal under Java's syntax rules, but it is difficult to read because of its layout and 2 | lack of comments. Reformat it using the rules given in Chapter 1, and add a comment header at the top of the program. 3 | 4 | (Practice-It isn't really able to check that you satisfied the requirements of this question. You will receive credit 5 | as long as you supply a reasonable amount of indentation and add two lines of // comments.) 6 | 7 | public 8 | class Messy{public 9 | static void main(String[]args){message () 10 | ;System.out.println() ; message ( );} public static void 11 | message() { System.out.println( 12 | "I really wish that" 13 | );System.out.println 14 | ("I had formatted my source") 15 | ;System.out.println("code correctly!");}} 16 | 17 | */ 18 | 19 | /*this is messy program and 20 | i try to clear it.*/ 21 | public class Messy { 22 |     public static void main(String[]args) {  23 |         message(); //I think its working! 24 |         System.out.println();  25 | message(); 26 | }  27 | public static void message() {  28 | System.out.println("I really wish that"); 29 | System.out.println("I had formatted my source"); 30 | System.out.println("code correctly!"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.1: MickeyBox.java: -------------------------------------------------------------------------------- 1 | /*Write a complete program in a class named MickeyBox that uses the DrawingPanel to draw the following figure: 2 | 3 | The window is 220 pixels wide and 150 pixels tall. The background is yellow. There are two blue ovals of size 40 x 40 pixels. 4 | The left oval's top-left corner is located at position (50, 25), and the two ovals' top-left corners are 80 pixels apart horizontally. 5 | There is a red square whose top two corners exactly intersect the centers of the two ovals. Lastly, there is a black horizontal line 6 | through the center of the square. 7 | 8 | (You don't need to include any import statements at the top of your program.) (The next exercise is a modified version of this 9 | program, so you can use the code you write here as a starting point for that exercise.)*/ 10 | 11 | public class MickeyBox { 12 | 13 | public static void main(String[] args) { 14 |         DrawingPanel panel = new DrawingPanel(220, 150); 15 |         panel.setBackground(new Color(255, 255, 0)); 16 |         Graphics g = panel.getGraphics(); 17 | 18 | g.setColor(Color.BLUE); 19 | g.fillOval(50, 25, 40, 40); 20 | g.fillOval(130, 25, 40, 40); 21 | g.setColor(Color.RED); 22 | g.fillRect(70, 45, 80, 80); 23 | g.setColor(Color.BLACK); 24 | g.drawLine(70, 85, 150, 85); 25 |     } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.7: Squares.java: -------------------------------------------------------------------------------- 1 | /*Write a program in a class named Squares that uses the DrawingPanel to draw the following figure: 2 | 3 | The drawing panel is 300 pixels wide by 200 pixels high. Its background is cyan. The horizontal and vertical lines are drawn in 4 | red and the diagonal line is drawn in black. The upper-left corner of the diagonal line is at (50,50). Successive horizontal 5 | and vertical lines are spaced 20 pixels apart. The diagonal line is drawn on top of the horizontal and vertical lines. 6 | 7 | (You don't need to include any import statements at the top of your program.) (The next two exercises are modified versions of 8 | this program, so you can use the code you write here as a starting point for those exercises.)*/ 9 | 10 | public class Squares { 11 |     public static void main(String[] args) { 12 |         DrawingPanel panel = new DrawingPanel(); 13 |         panel.setBackground(Color.CYAN); 14 |         panel.setSize(300, 200); 15 |         Graphics g = panel.getGraphics(); 16 |         g.setColor(Color.RED); 17 | g.drawRect(50, 50, 20, 20); 18 | g.drawRect(50, 50, 40, 40); 19 | g.drawRect(50, 50, 60, 60); 20 | g.drawRect(50, 50, 80, 80); 21 | g.drawRect(50, 50, 100, 100); 22 | g.setColor(Color.BLACK); 23 | g.drawLine(50, 50, 150, 150); 24 |     } 25 | } 26 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.3: Face.java: -------------------------------------------------------------------------------- 1 | /*Suppose you have the following existing program called Face that uses the DrawingPanel to draw a face figure. Modify the program 2 | to draw the graphical output shown below. Do so by writing a parameterized static method that draws a face at different positions. 3 | The window size should be changed to 320 x 180 pixels, and the two faces' top-left corners are at (10, 30) and (150, 50). 4 | 5 | (You don't need to include any import statements at the top of your program.) (The next exercise is a modified version of this program, 6 | so you can use the code you write here as a starting point for that exercise.)*/ 7 | 8 | public class Face { 9 |     public static void main(String[] args) { 10 |         DrawingPanel panel = new DrawingPanel(320, 180); 11 |         Graphics g = panel.getGraphics(); 12 |         drawingFace(g, 10, 30); 13 |         drawingFace(g, 150, 50); 14 |     } 15 |         public static void drawingFace(Graphics g, int x, int y) { 16 |         g.setColor(Color.BLACK); 17 |         g.drawOval(x, y, 100, 100);   // face outline 18 | 19 |         g.setColor(Color.BLUE); 20 |         g.fillOval(x + 20, y + 30, 20, 20);     // eyes 21 |         g.fillOval(x + 60, y + 30, 20, 20); 22 | 23 |         g.setColor(Color.RED);          // mouth 24 |         g.drawLine(x + 30, y + 70, x + 70, y + 70); 25 |     } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Self-Check 7.21: swapPairs.java: -------------------------------------------------------------------------------- 1 | /*Write a method named swapPairs that accepts an array of strings as a parameter and switches the order of values in a pairwise 2 | fashion. Your method should switch the order of the first two values, then switch the order of the next two, switch the order of 3 | the next two, and so on. For example, if the array initially stores these values: 4 | 5 | String[] a = {"four", "score", "and", "seven", "years", "ago"}; 6 | swapPairs(a); 7 | Your method should switch the first pair ("four", "score"), the second pair ("and", "seven") and the third pair ("years", "ago"), to yield this array: 8 | 9 | {"score", "four", "seven", "and", "ago", "years"} 10 | If there are an odd number of values, the final element is not moved. For example, if the original list had been: 11 | 12 | {"to", "be", "or", "not", "to", "be", "hamlet"} 13 | It would again switch pairs of values, but the final value ("hamlet") would not be moved, yielding this list: 14 | 15 | {"be", "to", "not", "or", "be", "to", "hamlet"} 16 | You may assume that the array is not null and that no element of the array is null.*/ 17 | public static void swapPairs(String[] s) { 18 |     for (int i = 0; i < s.length / 2; i++) { 19 |         String temp = s[2 * i]; 20 |         s[2 * i] = s[2 * i + 1]; 21 |         s[2 * i + 1] = temp; 22 |     } 23 |     System.out.println(Arrays.toString(s)); 24 | } 25 | -------------------------------------------------------------------------------- /Chapter 1- Introduction to Java Programming/Exercise 1.10: Egg2.java: -------------------------------------------------------------------------------- 1 | /*Write a complete Java program in a class named Egg2 that generates the following output. Use static methods to 2 | show structure and eliminate redundancy in your solution. 3 | 4 | _______ 5 | / \ 6 | / \ 7 | \ / 8 | \_______/ 9 | -"-'-"-'-"- 10 | _______ 11 | / \ 12 | / \ 13 | \ / 14 | \_______/ 15 | -"-'-"-'-"- 16 | \ / 17 | \_______/ 18 | _______ 19 | / \ 20 | / \ 21 | -"-'-"-'-"- 22 | \ / 23 | \_______/ 24 | */ 25 | 26 | public class Egg2 { 27 |     public static void main(String[] args) { 28 |         broukenEgg(); 29 |         egg(); 30 |     } 31 |     public static void broukenEgg() { 32 |         String top = "  _______" + "\n" + " /       \\" + "\n" + "/         \\" + "\n"; 33 |         String center = "-\"-'-\"-'-\"-" + "\n"; 34 |         String bottom = "\\         /" + "\n" + " \\_______/"; 35 |          36 |         System.out.println(top + bottom + "\n" + center + top + bottom + "\n" + center + bottom); 37 |          38 | } 39 |     public static void egg() { 40 |         String top = "  _______" + "\n" + " /       \\" + "\n" + "/         \\" + "\n"; 41 |         String center = "-\"-'-\"-'-\"-" + "\n"; 42 |         String bottom = "\\         /" + "\n" + " \\_______/" + "\n"; 43 |         System.out.println(top + center + bottom); 44 |     } 45 | } 46 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Exercise 4.16: printPalindrome.java: -------------------------------------------------------------------------------- 1 | /*Write a method called printPalindrome that accepts a Scanner for the console as a parameter, and prompts the user to enter one 2 | or more words and prints whether the entered String is a palindrome (i.e., reads the same forwards as it does backwards, like "abba" 3 | or "racecar"). If the following Scanner object were declared: 4 | 5 | 6 | Scanner console = new Scanner(System.in); 7 | printPalindrome(console); 8 | The resulting output for a call where the user types a palindrome would be: 9 | 10 | Type one or more words: racecar 11 | racecar is a palindrome! 12 | The output for a call where the user types a word that is not a palindrome would be: 13 | 14 | Type one or more words: hello 15 | hello is not a palindrome. 16 | For an added challenge, make the code case-insensitive, so that words like "Abba" and "Madam" will be considered palindromes.*/ 17 | 18 | public static void printPalindrome(Scanner console) { 19 | System.out.print("Type one or more words: "); 20 | String word = console.nextLine(); 21 | String string = word.toLowerCase(); 22 | int i = 0; 23 | int j = word.length() - 1; 24 | while(i < j) { 25 | if(string.charAt(i) != string.charAt(j)) { 26 | System.out.println(word + " is not a palindrome."); 27 | return; 28 | } 29 | i++; 30 | j--; 31 | } 32 | System.out.println(word + " is a palindrome!"); 33 | } 34 | -------------------------------------------------------------------------------- /Supplement 3G- Graphics/Exercise 3G.2: MickeyBox2.java: -------------------------------------------------------------------------------- 1 | /*Modify your MickeyBox program from the previous exercise into a new class MickeyBox2 so that the figure is drawn by a method 2 | called drawFigure. The method should accept three parameters: the Graphics g of the DrawingPanel on which to draw, and two ints 3 | specifying the (x, y) position of the top-left corner of the figure. Use the following heading for your method 4 | public static void drawFigure(Graphics g, int x, int y) 5 | Set your DrawingPanel's size to 450 x 150 pixels, and use your drawFigure method to place two figures on it. One figure should 6 | be at position (50, 25) and the other should be at position (250, 45).*/ 7 | 8 | public class MickeyBox2 { 9 | 10 | public static void main(String[] args) { 11 |         DrawingPanel panel = new DrawingPanel(450, 150); 12 |         panel.setBackground(new Color(255, 255, 0)); 13 |         Graphics g = panel.getGraphics(); 14 |         drawFigure(g, 50, 25); 15 |         drawFigure(g, 250, 45); 16 |     } 17 |         public static void drawFigure(Graphics g, int x, int y) { 18 |             g.setColor(Color.BLUE); 19 |             g.fillOval(x, y, 40, 40); 20 |             g.fillOval(x + 80, y, 40, 40); 21 |             g.setColor(Color.RED); 22 |             g.fillRect(x + 20, y + 20, 80, 80); 23 |             g.setColor(Color.BLACK); 24 |             g.drawLine(x + 20, y + 60, x + 100, y + 60); 25 |     } 26 |     27 | } 28 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.11: numbersOutputConstant.java: -------------------------------------------------------------------------------- 1 | /*Modify your code from the previous exercise so that it could easily be modified to display a different range of numbers 2 | (instead of 1234567890) and a different number of repetitions of those numbers (instead of 60 total characters), with the 3 | vertical bars still matching up correctly. Write a complete class named NumbersOutput. Use two class constants instead of "magic numbers,", with one constant set to 6 for the number of repetitions, and the other set to 10 for the range of numbers. Put the for loop code in your class's main method. 4 | 5 | For example, if your number-of-repetitions constant is set to 7 and your range constant is set to 5, the output should be the 6 | following: 7 | 8 | | | | | | | | 9 | 12340123401234012340123401234012340 10 | 11 | (You must solve this problem using only exactly two public static final constants, no more, no less.)*/ 12 | public class NumbersOutput { 13 |     public static final int repetitions = 6; 14 |     public static final int range = 10; 15 | 16 | public static void main(String[] args) { 17 | for(int k = 1; k <= repetitions; k++) { 18 | for(int i = 1; i < range; i++)  19 | System.out.print(" "); 20 | System.out.print("|"); 21 | } 22 | System.out.println(); 23 | for(int j = 1; j <= (range * repetitions); j++)  24 | System.out.print(j%range); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.25: printTriangleTypePreconditions.java: -------------------------------------------------------------------------------- 1 | /*Consider a method printTriangleType that accepts three integer arguments representing the lengths of the sides of a triangle and 2 | prints the type of triangle that these sides form. 3 | 4 | public static void printTriangleType(int a, int b, int c) { 5 | ... 6 | } 7 | 8 | The three types are equilateral, isosceles, and scalene. An equilateral triangle has three sides of the same length, an isosceles 9 | triangle has two sides that are the same length, and a scalene triangle has three sides of different lengths. However, certain 10 | integer values (or combinations of values) would be illegal and could not represent the sides of an actual triangle. What are 11 | these values? (In other words, how would you describe the precondition(s) of the printTriangleType method?) 12 | 13 | Which of the following are precondition(s) that are appropriate for this method? Check all that apply. 14 | 15 | a. The three side lengths must be positive integers. 16 | b. No side's length can be greater than 180. 17 | c. All sides must have the same length. 18 | d. No side's length may exceed the sum of any two other side lengths. 19 | e. No two sides' lengths can be the same. 20 | f. The sum of the sides' lengths must be an even number.*/ 21 | 22 | a. The three side lengths must be positive integers. 23 | d. No side's length may exceed the sum of any two other side lengths. 24 | -------------------------------------------------------------------------------- /Chapter 4- Conditional Execution/Self-Check 4.1: logicalTests.java: -------------------------------------------------------------------------------- 1 | /*Translate each of the following English statements into logical tests that could be used in an if/else statement. Write the 2 | appropriate logical test for each statement below. Assume that three int variables, x, y, and z, have already been declared. 3 | 4 | (Note: This problem is currently not very well implemented in Practice-It. Right now our system is just checking whether your 5 | answer exactly matches our expected answer, but some other correct answers might be marked as incorrect even though they would 6 | work. We plan to improve the system in the future. Sorry for the inconvenience.)*/ 7 | 8 | a. z is odd. z % 2 != 0; 9 | b. z is not greater than y's square root. z <= Math.sqrt(y); 10 | c. y is positive. y > 0; 11 | d. Either x or y is even, and the other is odd. (Hint: Don't use && or ||.) x % 2 != y % 2; 12 | e. y is a multiple of z. y % z == 0; 13 | f. z is not zero. z != 0; 14 | g. y is greater in magnitude than z. Math.abs(y) > Math.abs(z) 15 | h. x and z are of opposite signs. (x >= 0) == (z < 0) 16 | i. y is a nonnegative one-digit number. y % 10 == y 17 | j. z is nonnegative. z >= 0; 18 | k. x is even x % 2 == 0; 19 | l. x is closer in value to y than z is. Math.abs(x - y) < Math.abs(z - y); 20 | -------------------------------------------------------------------------------- /Chapter 7- Arrays/Exercise 7.11: isUnique.java: -------------------------------------------------------------------------------- 1 | /*Write a method named isUnique that takes an array of integers as a parameter and that returns a boolean value indicating whether or not the values in the array are unique (true for yes, false for no). The values in the list are considered unique if there is no pair of values that are equal. For example, if a variable called list stores the following values: 2 | 3 | 4 | int[] list = {3, 8, 12, 2, 9, 17, 43, -8, 46, 203, 14, 97, 10, 4}; 5 | Then the call of isUnique(list) should return true because there are no duplicated values in this list. If instead the list stored these values: 6 | 7 | 8 | int[] list = {4, 7, 2, 3, 9, 12, -47, -19, 308, 3, 74}; 9 | Then the call should return false because the value 3 appears twice in this list. Notice that given this definition, a list of 0 or 1 elements would be considered unique.*/ 10 | 11 | public static boolean isUnique(int[] array) { 12 | for (int i = 0; i < array.length; i++) { 13 | int min = array[i]; 14 | 15 | for (int j = i + 1; j < array.length; j++) { 16 | if (min > array[j]) { 17 | array[i] = array[j]; 18 | array[j] = min; 19 | min = array[i]; 20 | } 21 | } 22 | 23 | } 24 | 25 | for (int i = 0; i < array.length - 1; i++) { 26 | if (array[i] == array[i + 1]) { 27 | return false; 28 | } 29 | } 30 | 31 | return true; 32 | } 33 | -------------------------------------------------------------------------------- /Chapter 2- Primitive Data and Definite Loops/Exercise 2.23: DollarFigure2.java: -------------------------------------------------------------------------------- 1 | /*Modify your DollarFigure program from the previous exercise to become a new program called DollarFigure2 that uses a global constant for the figure's height. (You may want to make loop tables first.) The previous output used a constant height of 7. The outputs below use a constant size of 3 (left) and 5 (right): 2 | 3 | size 3 4 | $$$******$$$ 5 | **$$****$$** 6 | ****$**$**** 7 | 8 | size 5 9 | $$$$$**********$$$$$ 10 | **$$$$********$$$$** 11 | ****$$$******$$$**** 12 | ******$$****$$****** 13 | ********$**$******** 14 | 15 | (You must solve this problem using only ONE public static final constant, not multiple constants; and its value must be used 16 | in the way described in this problem.)*/ 17 | 18 | public class DollarFigure2 { 19 |     public static final int R= 5; 20 |      21 | public static void main(String[] args) { 22 | for(int i = 1; i <= R; i++) { 23 |             for(int j = 0; j < 2 * i - 2; j++) 24 |                 System.out.print("*"); 25 |             for(int j = 0; j <= -i + R; j++) 26 |                 System.out.print("$"); 27 |             for(int j = 0; j <= -2 * i + (R*2+1); j++) 28 |                 System.out.print("*"); 29 |             for(int j = 0; j <= -i + R; j++) 30 |                 System.out.print("$"); 31 |             for(int j = 0; j < 2 * i - 2; j++) 32 |                 System.out.print("*"); 33 |             System.out.println(); 34 | 35 | } 36 | } 37 | } 38 | --------------------------------------------------------------------------------