New Semester
Started
Get
50% OFF
Study Help!
--h --m --s
Claim Now
Question Answers
Textbooks
Find textbooks, questions and answers
Oops, something went wrong!
Change your search query and then try again
S
Books
FREE
Study Help
Expert Questions
Accounting
General Management
Mathematics
Finance
Organizational Behaviour
Law
Physics
Operating System
Management Leadership
Sociology
Programming
Marketing
Database
Computer Network
Economics
Textbooks Solutions
Accounting
Managerial Accounting
Management Leadership
Cost Accounting
Statistics
Business Law
Corporate Finance
Finance
Economics
Auditing
Tutors
Online Tutors
Find a Tutor
Hire a Tutor
Become a Tutor
AI Tutor
AI Study Planner
NEW
Sell Books
Search
Search
Sign In
Register
study help
computer science
building java programs a back to basics approach
Building Java Programs A Back To Basics Approach 5th Edition Stuart Reges, Marty Stepp - Solutions
Write a method called printSquare that accepts a minimum and maximum integer and prints a square of lines of increasing numbers. The first line should start with the minimum, and each line that follows should start with the next-higher number. The sequence of numbers on a line wraps back to the
Write a program that prompts for the lengths of the sides of a triangle and reports the three angles.
What output is produced by the following program? 1 public class Odds { public static void main (String [] args) { printOdds (3); 4 printodds (17 / 2); int x = 25; printodds (37 - x + 1); 8 9. 10 public static void printOdds (int n) { 11 for (int i 1; i
The following code attempts to draw a black rectangle from (10, 20) to (50, 40) with a line across its diagonal:DrawingPanel panel = new DrawingPanel(200, 100);Graphics g = panel.getGraphics();g.drawRect(10, 20, 50, 40);g.drawLine(10, 20, 50, 40);However, the graphical output looks like Figure
Modify your previous Face program to draw the new output shown in Figure 3G.25. The window size should be changed to pixels, and the faces’ top-left corners are at (10, 30), (110, 30), (210, 30), (310, 30), and (410, 30). L Drawing Panel File View Help
Write a modified version of the Projectile case study program from Chapter 3 that draws a graph of the projectile’s flight onto a DrawingPanel of size 420 × 220. For example, the panel shown in Figure 3G.38 draws a projectile with an initial velocity of 30 meters per second, an angle of 50
Write a program that draws the image shown in Figure 3G.39 onto a DrawingPanel of size 650 × 400. The image represents a famous optical illusion called the “Cafe Wall,” in which a series of straight squares appears to be slanted.The image has a gray background and many rows of black and white
Write a method called printGrid that accepts two integers representing a number of rows and columns and prints a grid of integers from 1 to (rows * columns) in column major order. For example, the callprintGrid(4, 6);should produce the following output:1 5 9 13 17 212 6 10 14 18 223 7 11 15 19 234
Write a program that computes the spherical distance between two points on the surface of the Earth, given their latitudes and longitudes. This is a useful operation because it tells you how far apart two cities are if you multiply the distance by the radius of the Earth, which is roughlyLet φ1,
What is the output of the following program? 1 public class Weird { public static void main (String [] args) { int number 8; %3D 4 halfTheFun (11); halfTheFun (2 - 3 + 2 * 8); halfTheFun (number); 7 System.out.println ("number = " + number); 8. 9. 10 public static void halfTheFun (int number) { 11
What sort of figure will be drawn by the following program? Can you draw a picture that will approximately match its appearance without running it first? 1 import java.awt.*; 3 public class Draw7 { public static void main (String[] args) { DrawingPanel panel = new DrawingPanel (200, 200) ; 6.
Write a program called ShowDesign that uses the DrawingPanel to draw Figure 3G.26.The window is 200 pixels wide and 200 pixels tall. The background is white and the foreground is black. There are 20 pixels between each of the four rectangles, and the rectangles are concentric (their centers are at
Write a method called largerAbsVal that takes two integers as parameters and returns the larger of the two absolute values. A call of largerAbsVal(11, 2) would return 11 , and a call of largerAbsVal(4, –5) would return 5.
Write a program that produces calendars as output. Your program should have a method that outputs a single month’s calendar like the one below, given parameters to specify how many days are in the month and what the date of the first Sunday is in that month. In the month shown below, these values
What is the output of the following program? 1. public class MysteryNumbers { public static void main (String [] args) { 3. String one = "two"; 4 String two = "three"; String three = "1"; int number = 20; 7. B sentence (one, two, 3) ; 9. sentence (two, three, l14); 10 sentence (three, three, number
Modify your ShowDesign program from the previous exercise so that it has a method that accepts parameters for the window width and height and displays the rectangles at the appropriate sizes. For example, if your method was called with values of 300 and 100, the window would look like Figure
Write a variation of the largestAbsVal method from the last exercise that takes three integers as parameters and returns the largest of their three absolute values. For example, a call of largestAbsVal(7, –2, – 11) would return 11 , and a call of largestAbsVal(-4, 5, 2) would return 5.
What output is produced by the following program? 1 public class MysteryWho { public static void main (String [] args) { 3 String whom "her"; 4 String who "him"; String it = "who"; String he = "it"; 7 String she "whom"; %3D 9. sentence (he, she, it); 10 sentence (she, he, who); 11 sentence (who,
Write a program called Squares that uses the DrawingPanel to draw the shape shown in Figure 3G.28.The DrawingPanel is 300 pixels wide by 200 pixels high. Its background is cyan. The horizontal and vertical lines are drawn in red and the diagonal line is drawn in black. The upper-left corner of the
Write a method called quadratic that solves quadratic equations and prints their roots. Recall that a quadratic equation is a polynomial equation in terms of a variable of the form ax2 + bx + c = 0. The formula for solving a quadratic equation isHere are some example equations and their roots:x2
What output is produced by the following program? 1 public class MysteryTouch ( 2. public static void main (String[] args) { 3 String head = "shoulders"; String knees = "toes"; String elbow "head"; String eye = "eyes and ears"; 7 String ear "eye"; 9. touch (ear, elbow) ; 10 touch (elbow, ear); 11
Modify your code from the previous exercise to produce the pattern shown in Figure 3G.29.The DrawingPanel is now 400 x 300 pixels in size. The first figure is at the same position, (50, 50). The other figures are at positions (250, 10) and (180, 115), respectively. Use one or more parameterized
Write a method called lastDigit that returns the last digit of an integer. For example, lastDigit(3572) should return 2. It should work for negative numbers as well. For example, lastDigit(-947) should return 7.
What output is produced by the following program? public class MysterySoda { public static void main (String[] args) { String soda "Coke"; %3D 4 String pop "Pepsi"; String Coke "роp"; %3D String Pepsi "soda"; 7 String say pop; 8. carbonated (Coke, soda, pop); 10 carbonated (pop, Pepsi, Pepsi); 11
Modify your code from the previous exercise to produce the pattern shown in Figure 3G.30.The DrawingPanel is the same except that now each figure has a different size. The left figure has its original size of 100, the top-right figure has a size of 50, and the bottom-right figure has a size of 180.
Write a method called area that accepts as a parameter the radius of a circle and that returns the area of the circle. For example, the call area(2.0) should return 12.566370614359172. Recall that area can be computed as pi (π) times the radius squared and that Java has a constant called Math.PI.
Write a method called printStrings that accepts a String and a number of repetitions as parameters and prints that String the given number of times with a space after each time. For example, the callprintStrings("abc", 5);will print the following output:abc abc abc abc abc
Write a program called Stairs that uses the DrawingPanel to draw the figure shown in Figure 3G.31. The first stair’s top-left corner is at position (5, 5). The first stair is 10 × 10 pixels in size. Each stair is 10 pixels wider than the one above it. Make a table with the (x, y) coordinates and
Write a method called distance that accepts four integer coordinates x1, y1, x2 and y2 as parameters and computes the distance between points (x1, y1) and (x2, y2) on the Cartesian plane. The equation for the distance isFor example, the call of distance(1, 0, 4, 4) would return 5.0 and the call of
The System.out.println command works on many different types of values, such as integers or doubles . What is the term for such a method?
Modify your previous Stairs program to draw each of the outputs shown in Figure 3G.32. Modify only 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.) Dr... File View Help
Write a method called scientific that accepts a real number base and an exponent as parameters and computes the base times 10 to the exponent, as seen in scientific notation. For example, the call of scientific(6.23, 5) would return 623000.0 and the call of scientific(1.9, –2) would return 0.019.
What is wrong with the following program?
Write a program called Triangle that uses the DrawingPanel to draw the figure shown in Figure 3G.33.The window is 600 × 200 pixels in size. The background is yellow and the lines are blue. The lines are 10 pixels apart vertically, and the diagonal lines intersect at the bottom of the figure in its
Write a method called pay that accepts two parameters: a real number for a TA’s salary, and an integer for the number of hours the TA worked this week. The method should return how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. The TA should receive
Write a program called Football that uses the DrawingPanel to draw the figure shown in Figure 3G.34. Though the figure looks to contain curves, it is entirely made of straight lines.The window is 250 x 250 pixels in size. There is an outer rectangle from (10, 30) to (210, 230), and a set of black
Evaluate the following expressions:a. Math.abs(–1.6)b. Math.abs(2 + –4)c. Math.pow(6, 2)d. Math.pow(5 / 2, 6)e. Math.ceil(9.1)f. Math.ceil(115.8)g. Math.max(7, 4)h. Math.min(8, 3 + 2)i. Math.min(–2, –5)j. Math.sqrt(64)k. Math.sqrt(76 + 45)l. 100 + Math.log10(100)m. 13 + Math.abs(–7) –
Write a method called cylinderSurfaceArea that accepts a radius and height as parameters and returns the surface area of a cylinder with those dimensions. For example, the call cylinderSurfaceArea(3.0, 4.5) should return 141.3716694115407. The formula for the surface area of a cylinder with radius
What output is produced by the following program? public class MysteryReturn { 2. public static void main (String[] args) { 3 int x = 1, y = 2, z = 3; z = mystery (x, z, y); System.out.println (x + " " + y + " " + z); 6. x = mystery (z, z, x); System.out.println (x + + y + " " + z); 8. y = mystery
Write a method called sphereVolume that accepts a radius as a parameter and returns the volume of a sphere with that radius. For example, the call sphereVolume(2.0) should return 33.510321638291124 . The formula for the volume of a sphere with radius is the following: volume 4 /37Tp3
Write the result of each expression. Note that a variable’s value changes only if you reassign it using the = operator. double grade = 2.7; Math.round (grade); // grade grade = Math.round (grade); // grade double min Math.min (grade, Math.floor (2.9)); // min = double x = Math.pow (2, 4); // x =
Write a method called triangleArea that accepts the three side lengths of a triangle as parameters and returns the area of a triangle with those side lengths. For example, the call triangleArea(8, 5.2, 7.1) should return 18.151176098258745 . To compute the area, use Heron’s formula, which states
Write a method called min that takes three integers as parameters and returns the smallest of the three values; for example, 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.
Write a method called padString that accepts two parameters: a string and an integer representing a length. The method should pad the parameter string with spaces until its length is the given length. For example, padString("hello", 8) should return "hello " . (This sort of method is useful when
Write a method called countQuarters that takes an int representing a number of cents as a parameter and returns the number of quarter coins represented by that many cents. Don’t count any whole dollars, because those would be dispensed as dollar bills. For example, countQuarters(64) would return
Write a method called vertical that accepts a string as its parameter and prints each letter of the string on separate lines. For example, a call of vertical("hey now") should produce the following output:heynow
What output is produced by the following code?String first = "James";String last = "Kirk";String middle = "T.";System.out.println(last);System.out.println("My name is " + first);System.out.println(first + " " + last);System.out.println(last + ", " + first + " " + middle);System.out.println(middle +
Write a method called printReverse that accepts a string as its parameter and prints the characters in opposite order. For example, a call of printReverse("hello there!") should print "!ereht olleh". If the empty string is passed, the method should produce no output.
Assuming that the following variables have been declared:evaluate the following expressions:a. str1.length()b. str1.charAt(7)c. str2.charAt(0)d. str1.indexOf("o")e. str2.toUpperCase()f. str1.toLowerCase().indexOf("B")g. str1.substring(4)h. str2.substring(3, 14)i. str2.replace("a", "oo")j.
Write a method called inputBirthday that accepts a Scanner for the console as a parameter and prompts the user to enter a month, day, and year of birth, then prints the birthdate in a suitable format. Here is an example dialogue with the user:On what day of the month were you born? 8What is the
Assuming that the following variables have been declared:String str1 = "Q.E.D.";String str2 = "Arcturan Megadonkey";String str3 = "Sirius Cybernetics Corporation";evaluate the following expressions:a. str1.length()b. str2.length()c. str1.toLowerCase()d. str2.toUpperCase()e. str1.substring(2, 4)f.
Consider the following String:String quote = "Four score and seven years ago";What expression produces the new String "SCORE"? What expression produces "four years"?
Write a method called processName that accepts a Scanner for the console as a parameter and prompts the user to enter a full name, then prints the name in reverse order (i.e., last name, first name). Here is an example dialogue with the user:Please enter your full name: Sammy JankisYour name in
Write a program that outputs “The Name Game,” where the user inputs a first and last name and a song is printed about their first, then last, name. Use a method to avoid redundancy.
Consider the following code fragment:Scanner console = new Scanner(System.in);System.out.print("How much money do you have? ");double money = console.nextDouble();Describe what will happen when the user types each of the following values. If the code will run successfully, describe the value that
Write a method called printIndexed that accepts a string as its parameter and prints the string’s characters in order followed by their indexes in reverse order. For example, the call of printIndexed("ZELDA") should print Z4E3L2D1A0 to the console.
Write Java 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.
Consider the following program. Modify the code to use a Scanner to prompt the user for the values of low and high .Below is a sample execution in which the user asks for the sum of the values 1 through 10:low? 1high? 10sum = 55 public class SumNumbers { public static void main (String[] args) { 3.
Write Java code that prompts the user for a phrase and a number of times to repeat it, then prints the phrase the requested number of times. Here is an example dialogue with the user:What is your phrase? His name is Robert Paulson.How many times should I repeat it? 3His name is Robert Paulson.His
Write a program that prompts for a number and displays it in Roman numerals.
Write a method called repl that accepts a String and a number of repetitions as parameters and returns the String concatenated that many times. For example, the call repl( "hello", 3) should return "hellohellohello". If the number of repetitions is zero or less, the method should return an empty
Given the variable declarationsint x = 4;int y = –3;int z = 4;what are the results of the following relational expressions?a. x == 4b. x == yc. x == zd. y == ze. x + y > 0f. x – z != 0g. y * y <= zh. y / y == 1i. x * (y + 2) > y - (y + z) * 2
Write a program that prompts for a date (month, day, year) and reports the day of the week for that date. It might be helpful to know that January 1, 1601, was a Monday.
Write a method called season that takes as parameters two integers representing a month and day and returns a String indicating the season for that month and day. Assume that the month is specified as an integer between 1 and 12 (1 for January, 2 for February, and so on) and that the day of the
Which of the following if statement headers uses the correct syntax?a. If x = 10 then {b. If [x == 10] {c. If (x => y) {d. If (x equals 42) {e. If (x == y) {
Write a program that compares two college applicants. The program should prompt for each student’s GPA, SAT, and ACT exam scores and report which candidate is more qualified on the basis of these scores.
Write a method called daysInMonth that takes a month (an integer between 1 and 12) as a parameter and returns the number of days in that month in this year. For example, the call daysInMonth(9) would return 30 because September has 30 days. Assume that the code is not being run during a leap year
The following program contains 7 mistakes! What are they?What output is produced for each of the following calls?a. IfElseMystery1(3, 20);b. IfElseMystery1(4, 5);c. IfElseMystery1(5, 5);d. IfElseMystery1(6, 10); 1 1 public class Oops4 { 2. public static void main (String[] args) { 3. int a = 7, b =
Write a program that prompts for two people’s birthdays (month and day), along with today’s month and day. The program should figure out how many days remain until each user’s birthday and which birthday is sooner
Write a method called pow that accepts a base and an exponent as parameters and returns the base raised to the given power. For example, the call pow(3, 4) should return 3 * 3 * 3 * 3, or 81. Assume that the base and exponent are nonnegative.
Write a method called printRange that accepts two integers as arguments and prints the sequence of numbers between the two arguments, separated by spaces. Print an increasing sequence if the first argument is smaller than the second; otherwise, print a decreasing sequence. If the two numbers are
Consider the following method:
A useful technique for catching typing errors is to use a check digit. For example, suppose that a school assigns a six-digit number to each student. A seventh digit can be determined from the other digits with the use of the following formula:7th digit = (1 * (1st digit) + 2 * (2nd digit)+. . .+6
Write a static method called xo that accepts an integer size as a parameter and prints a square of size by size characters, where all characters are “o” except that an “x” pattern of “x” characters has been drawn from the corners of the square. On the first line, the first and last
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 assume that the user types a valid integer.
Write a program that displays Pascal’s triangle:Use System.out.printf to format the output into fields of width 4. 1 1 1 3 4 6. 4 1 1 10 10 15 20 15 6 1 21 35 35 21 7 1 8. 28 56 70 56 28 8. 1 9. 36 84 126 126 84 36 10 45 120 210 252 210 120 45 10 w.
Write a method called smallestLargest that accepts a Scanner for the console as a parameter and asks the user to enter numbers, then prints the smallest and largest of all the numbers supplied by the user. You may assume that the user enters a valid number greater than 0 for the number of numbers
The following code contains a logic error:Examine the code and describe a case in which the code would print something that is untrue about the number that was entered. Explain why. Then correct the logic error in the code. Scanner console = new Scanner (System.in); System.out.print ("Type a
Write a program that produces a Caesar cipher of a given message string. A Caesar cipher, or rotation cipher, is formed by rotating each letter of a message by a given amount. For example, if you rotate by 3, every A becomes D; every B becomes E; and so on. Toward the end of the alphabet, you wrap
Write a method called evenSumMax that accepts a Scanner for the console as a parameter. The method should prompt the user for a number of integers, then prompt the integer that many times. Once the user has entered all the integers, the method should print the sum of all the even numbers the user
Write a method called printGPA that accepts a Scanner for the console as a parameter and calculates a student’s grade point average. The user will type a line of input containing the student’s name, then a number that represents the number of scores, followed by that many integer scores. Here
Factor out redundant code from the following example by moving it out of the if/else statement, preserving the same output. if (x < 30) { a = 2; x++; System.out.println ("Java is awesome! + x); } else { a = 2; System.out.println ("Java is awesome! + x);
Write a method called longestName that accepts a Scanner for the console and an integer as parameters and prompts for names, then prints the longest name (the name that contains the most characters) in the format shown below, which might result from a call of longestName(console, 4):name #1?
The following code is poorly structured:Rewrite it so that it has a better structure and avoids redundancy. To simplify things, you may assume that the user always types 1 or 2. (How would the code need to be modified to handle any number that the user might type?) int sum = 1000; Scanner console
Write the method called printTriangleType referred to in Self-Check Problem 25. This method accepts three integer arguments representing the lengths of the sides of a triangle and prints the type of triangle that these sides form. Here are some sample calls to printTriangleType:printTriangleType(5,
The following code is poorly structured:Rewrite it so that it has a better structure and avoids redundancy. You may wish to introduce a method to help capture redundant code. Scanner console = new Scanner (System.in); System.out.print ("How much will John be spending? "); double amount =
Write a method called average that takes two integers as parameters and returns the average of the two integers.
Write a piece of code that reads a shorthand text description of a color and prints the longer equivalent. Acceptable color names 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 print an error message. Make your program
Modify your pow method from Exercise 5 to make a new method called pow2 that uses the type double for the first parameter and that works correctly for negative numbers. For example, the call pow2(–4.0, 3) should return –4.0 * –4.0 * –4.0 , or –64.0 , and the call pow2(4.0, –2) should
Write a piece of code that reads a shorthand text description of a playing card and prints the longhand equivalent. The shorthand description is the card’s rank ( 2 through 10, J, Q, K, or A ) followed by its suit ( C, D, H, or S ). You should expand the shorthand into the form “ of ”. You
Write a method called getGrade that accepts an integer representing a student’s grade in a course and returns that student’s 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 and that grades are based on the
What is wrong with the following code, which attempts to add all numbers from 1 to a given maximum? Describe how to fix the code. public static int sumTo (int n) { for (int i = 1; i
Write a method called printPalindrome that accepts a Scanner for the console as a parameter, prompts the user to enter one or more words, and prints whether the entered String is a palindrome (i.e., reads the same forward as it does backward, like "abba" or "racecar ") .For an added challenge, make
What is wrong with the following code, which attempts to return the number of factors of a given integer n? Describe how to fix the code. public static int countFactors (int n) { for (int i = 1; i
Write a method called stutter that accepts a string parameter and returns that string with its characters repeated twice. For example, stutter("Hello!") returns "HHeelllloo!!"
Write code to produce a cumulative product by multiplying together many numbers that are read from the console.
Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String . A word is a sequence of one or more nonspace characters (any character other than ' '). For example, the call wordCount( "hello ") should return 1, the call wordCount( "how are
The following expression should equal 6.8 , but in Java it does not. Why not?0.2 + 1.2 + 2.2 + 3.2
Write a method called quadrant that accepts as parameters a pair of double values representing an (x, y) point and returns the quadrant number for that point. Recall that quadrants are numbered as integers from 1 to 4 with the upper-right quadrant numbered 1 and the subsequent quadrants numbered in
The following code was intended to print a message, but it actually produces no output. Describe how to fix the code to print the expected message. double gpa 3.2; if (gpa * 3 9.6) { == System.out.println ("You earned enough credits.");
Showing 800 - 900
of 1041
1
2
3
4
5
6
7
8
9
10
11
Step by Step Answers