chapter 5

¡Supera tus tareas y exámenes ahora con Quizwiz!

Convert each of the following for loops into an equivalent while loop. (You might need to rename some variables for the code to compile, since all four parts a-d are in the same scope.) // a. System.out.println("a."); int max = 5; for (int n = 1; n <= max; n++) { System.out.println(n); } System.out.println(); // b. System.out.println("b."); int total = 25; for (int number = 1; number <= (total / 2); number++) { total = total - number; System.out.println(total + " " + number); } System.out.println(); // c. System.out.println("c."); for (int i = 1; i <= 2; i++) { for (int j = 1; j <= 3; j++) { for (int k = 1; k <= 4; k++) { System.out.print("*"); } System.out.print("!"); } System.out.println(); } System.out.println(); // d. System.out.println("d."); int number = 4; for (int count = 1; count <= number; count++) { System.out.println(number); number = number / 2; }

// a. System.out.println("a."); int n=1; int max = 5; while (n <= max){ System.out.println(n); n++; } System.out.println(); // b. System.out.println("b."); int total = 25; int number=1; while (number <= (total / 2)) { total = total - number; System.out.println(total + " " + number); number++; } System.out.println(); // c. System.out.println("c."); int i=1; while (i <= 2){ int j=1; while( j <= 3) { int k=1; while (k <= 4) { System.out.print("*"); k++; } System.out.print("!"); j++; } System.out.println(); i++; } System.out.println(); // d. System.out.println("d."); int num = 4; int count=1; while (count <= num) { System.out.println(num); num = num / 2; count++; }

Given the following method: public static int mystery(int x, int y) { while (x != 0 && y != 0) { if (x < y) { y = y - x; } else { x = x - y; } } return x + y; } Write the value returned by each of the following calls. mystery(3, 3) mystery(5, 3) mystery(2, 6) mystery(12, 18) mystery(30, 75)

3 1 2 6 15

For each of the following while loops, how many times will the loop execute its body? Remember that "zero," "infinity," and "unknown" are legal answers. a) int x = 1; while (x < 100) { System.out.print(x + " "); x += 10; } b) int max = 10; while (max < 10) { System.out.println("count down: " + max); max--; } c) int x = 250; while (x % 3 != 0) { System.out.println(x); } d) int x = 2; while (x < 200) { System.out.print(x + " "); x *= x; } e) String word = "a"; while (word.length() < 10) { word = "b" + word + "b"; } System.out.println(word); f) int x = 100; while (x > 0) { System.out.println(x / 10); x = x / 2; }

a. 10 b. 0 c. infinity d. 3 e. 5 f. 7

Write a method named allDigitsOdd that returns whether every digit of a given integer is odd. Your method should return true if the number consists entirely of odd digits and false if any of its digits are even. 0, 2, 4, 6, and 8 are even digits, and 1, 3, 5, 7, 9 are odd digits. Your method should work for positive and negative numbers. For example, here are some calls to your method and their expected results: Call Value Returned allDigitsOdd(4822116) false allDigitsOdd(135319) true allDigitsOdd(9175293) false allDigitsOdd(-137) true You should not use a String to solve this problem.

public boolean allDigitsOdd(int x) { x = Math.abs(x); int digit; if ( x == 0){ return false; } while (x > 0) { digit = x % 10; if (digit % 2 == 0){ return false; } x /= 10; } return true; }

Write a method named hasAnOddDigit that returns whether any digit of a positive integer is odd. Your method should return true if the number has at least one odd digit and false if none of its digits are odd. 0, 2, 4, 6, and 8 are even digits, and 1, 3, 5, 7, 9 are odd digits. For example, here are some calls to your method and their expected results: Call Value Returned hasAnOddDigit(4822116) true hasAnOddDigit(2448) false hasAnOddDigit(-7004) true You should not use a String to solve this problem.

public boolean hasAnOddDigit(int x) { x = Math.abs(x); int digit; while (x > 0) { digit = x % 10; if (digit % 2 == 1) return true; x /= 10; } return false; }

Write a method named monthApart that accepts four integer parameters representing two calendar dates. Each date consists of a month (1 through 12) and a day (1 through the number of days in that month [28-31]). The method returns whether the dates are at least a month apart. Assume that all dates in this problem occur during the same year. For example, the following dates are all considered to be at least a month apart from 9/19 (September 19): 2/14, 7/25, 8/2, 8/19, 10/19, 10/20, and 11/5. The following dates are NOT at least a month apart from 9/19: 9/20, 9/28, 10/1, 10/15, and 10/18. Note that the first date could come before or after (or be the same as) the second date. Assume that all parameter values passed are valid. Sample calls: Call Returns Because monthApart( 6, 14, 9, 21) true June 14th is at least a month before September 21st monthApart( 4, 5, 5, 15) true April 5th is at least a month before May 15th monthApart( 4, 15, 5, 15) true April 15th is at least a month before May 15th monthApart( 4, 16, 5, 15) false April 16th is NOT at least a month before May 15th monthApart( 6, 14, 6, 8) false June 14th is NOT at least a month apart from June 8th monthApart( 7, 7, 6, 8) false July 7th is NOT at least a month apart from June 8th monthApart( 7, 8, 6, 8) true July 8th is at least a month after June 8th monthApart( 10, 14, 7, 15) true October 14th is at least a month after July 15th

public boolean monthApart(int m1, int d1, int m2, int d2) { int md = Math.abs(m1 - m2); if (md >= 2) { return true; } if (md == 0) { return false; } if (m1 > m2) { if (d1 >= d2) { return true; } else { return false; } } else { if (d2 >= d1) { return true; } else { return false; } } }

Write a method named digitRange that accepts an integer as a parameter and returns the range of values of its digits. The range is defined as 1 more than the difference between the largest and smallest digit value. For example, the call of digitRange(68437) would return 6 because the largest digit value is 8 and the smallest is 3, so 8 - 3 + 1 = 6. If the number contains only one digit, return 1. You should solve this problem without using a String.

public int digitRange(int n) { n = Math.abs(n); if (n < 10) { return 1; } int min= n % 10; int max= min; int last; while(n>0) { last = n % 10; if (last < min) { min = last; } if (last > max) { max = last; } n /= 10; } return max-min+1; }

Write a static method named anglePairs that accepts three angles (integers), measured in degrees, as parameters and returns whether or not there exists both complementary and supplementary angles amongst the three angles passed. Two angles are complementary if their sum is exactly 90 degrees; two angles are supplementary if their sum is exactly 180 degrees. Therefore, the method should return true if any two of the three angles add up to 90 degrees and also any two of the three angles add up to 180 degrees; otherwise the method should return false. You may assume that each angle passed is non-negative. Here are some example calls to the method and their resulting return values. Call Value Returned anglePairs(0, 90, 180) anglePairs(45, 135, 45) anglePairs(177, 87, 3) anglePairs(120, 60, 30) anglePairs(35, 60, 30) anglePairs(120, 60, 45) anglePairs(45, 90, 45) anglePairs(180, 45, 45) true true true true false false false false

public static boolean anglePairs(int x,int y,int z){ return ((x+y==90 || x+z==90 || y+z ==90) && (x+y ==180||y+z ==180 || z+x==180)); }

Write a method named consecutive that accepts three integers as parameters and returns true if they are three consecutive numbers; that is, if the numbers can be arranged into an order such that there is some integer k such that the parameters' values are k, k+1, and k+2. Your method should return false if the integers are not consecutive. Note that order is not significant; your method should return the same result for the same three integers passed in any order. For example, the calls consecutive(1, 2, 3), consecutive(3, 2, 4), and consecutive(-10, -8, -9) would return true. The calls consecutive(3, 5, 7), consecutive(1, 2, 2), and consecutive(7, 7, 9) would return false.

public static boolean consecutive(int a, int b, int c) { int small=Math.min(a, Math.min(b,c)); return (a+b+c ==small+(small+1)+ (small+2)); }

The following code attempts to examine a String and return whether it contains a given letter. A flag named found is used. However, the Boolean logic is not implemented correctly, so the method does not always return the correct answer. In what cases does the method report an incorrect answer? Change the code so that it will always return a correct result. public static boolean contains(String str, char ch) { boolean found = false; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { found = true; } else { found = false; } } return found; }

public static boolean contains(String str, char ch) { boolean found = false; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { found = true; } } return found; }

Write a method named hasMidpoint that accepts three integers as parameters and returns true if one of the integers is the midpoint between the other two integers; that is, if one integer is exactly halfway between them. Your method should return false if no such midpoint relationship exists. The integers could be passed in any order; the midpoint could be the 1st, 2nd, or 3rd. You must check all cases. Calls such as the following should return true: hasMidpoint(4, 6, 8) hasMidpoint(2, 10, 6) hasMidpoint(8, 8, 8) hasMidpoint(25, 10, -5) Calls such as the following should return false: hasMidpoint(3, 1, 3) hasMidpoint(1, 3, 1) hasMidpoint(21, 9, 58) hasMidpoint(2, 8, 16)

public static boolean hasMidpoint(int x,int y, int z){ int max=Math.max(Math.max(x,y),z); double middle=(x+y+z)/3.0; int min=Math.min(Math.min(x,y),z); return (max-middle==middle-min); }

Write a method named isAllVowels that returns whether a String consists entirely of vowels (a, e, i, o, or u, case-insensitively). If every character of the String is a vowel, your method should return true. If any character of the String is a non-vowel, your method should return false. Your method should return true if passed the empty string, since it does not contain any non-vowel characters. For example, here are some calls to your method and their expected results: Call Value Returned isAllVowels("eIEiO") true isAllVowels("oink") false

public static boolean isAllVowels(String phrase){ String wordy; for(int i=0;i<phrase.length();i++){ wordy = phrase.substring(i, i+ 1); if(!(wordy.equalsIgnoreCase("a") || wordy.equalsIgnoreCase("e") || wordy.equalsIgnoreCase("i") || wordy.equalsIgnoreCase("o") || wordy.equalsIgnoreCase("u"))){ return false; } } return true; }

The following method attempts to examine a number and return whether that number is prime (i.e., has no factors other than 1 and itself). A flag named prime is used. However, the Boolean logic is not implemented correctly, so the method does not always return the correct answer. In what cases does the method report an incorrect answer? Find the problem and change the code so that it will always return a correct result.public static boolean isPrime(int n) { boolean prime = true; for (int i = 2; i < n; i++) { if (n % i == 0) { prime = false; } else { prime = true; } } return prime; }

public static boolean isPrime(int n) { int count=0; for (int i = 1; i <= n; i++) { if (n%i==0){ count++; } } return (count==2); }

rite a method named isVowel that returns whether a String is a vowel (a single-letter string containing a, e, i, o, or u, case-insensitively).

public static boolean isVowel(String word){ return (word.equalsIgnoreCase("a")|| word.equalsIgnoreCase("e")|| word.equalsIgnoreCase("i")|| word.equalsIgnoreCase("o")|| word.equalsIgnoreCase("u")); }

Using "Boolean Zen," write an improved version of the following method, which returns whether the given string starts and ends with the same character. (In other words, remove unnecessary logical tests and remove if/else statements that test the value of a boolean variable.) public static boolean startEndSame(String str) { if (str.charAt(0) == str.charAt(str.length() - 1)) { return true; } else { return false; } }

public static boolean startEndSame(String str) { return str.charAt(0) == str.charAt(str.length() - 1) ; }

Write a method named digitSum that accepts an integer as a parameter and returns the sum of the digits of that number. For example, digitSum(29107) returns 2+9+1+0+7 or 19. For negative numbers, return the same value that would result if the number were positive. For example, digitSum(-456) returns 4+5+6 or 15.

public static int digitSum(int num){ int sum=0; while(Math.abs(num)>0){ sum+=num%10; num/=10; } return Math.abs(sum); }

Write a method named firstDigit that returns the first digit of an integer. For example, firstDigit(3572) should return 3. It should work for negative numbers as well. For example, firstDigit(-947) should return 9. Call Value Returned firstDigit(3572) 3 firstDigit(-947) 9 firstDigit(6) 6 firstDigit(35) 3 firstDigit(123456) 1 (Hint: Use a while loop. You may not use a String to solve this problem.)

public static int firstDigit(int n){ n=Math.abs(n); while (n >= 10) { n /= 10; } return n; }

Write a method called zeroDigits that accepts an integer parameter and returns the number of digits in the number that have the value 0. For example, the call zeroDigits(5024036) should return 2, and zeroDigits(743) should return 0. The call zeroDigits(0) should return 1. You may assume that the integer is non-negative. (We suggest you use a do/while loop in your solution.)

public static int zeroDigits(int number) { int count = 0; do { if (number % 10 == 0) { count++; } number = number / 10; } while (number > 0); return count; }

Write a method named diceSum that prompts the user for a desired sum, then repeatedly rolls two six-sided dice until their sum is the desired sum. Here is the expected dialogue with the user: Desired dice sum: 9 4 and 3 = 7 3 and 5 = 8 5 and 6 = 11 5 and 6 = 11 1 and 5 = 6 6 and 3 = 9

public static void diceSum(){ Random rand=new Random(); Scanner console=new Scanner (System.in); System.out.print("Desired dice sum: "); int n=console.nextInt(); int x, y,sum; do { x = rand.nextInt(6) +1; y = rand.nextInt(6) +1; sum = x + y; System.out.println(x + " and " + y + " = " + sum); } while (sum != n); }

Consider the flawed method printLetters that follows, which accepts a string as its parameter and attempts to print the letters of the string, separated by dashes. For example, the call of printLetters("Rabbit") should print R-a-b-b-i-t. The initial code shown is incorrect. Correct it to produce the desired behavior. (Your method should print nothing if the empty string ("") is passed.) public static void printLetters(String text) { for (int i = 0; i < text.length(); i++) { System.out.print(text.charAt(i) + "-"); } System.out.println(); // to end the line of output }

public static void printLetters(String text) { if(text.length()>0){ System.out.print(text.charAt(0)); for (int i = 1; i < text.length(); i++) { System.out.print( "-"+text.charAt(i) ); } } System.out.println(); }

Write a method called randomLines that prints between 5 and 10 random strings of letters (between "a" and "z"), one per line. Each string should have random length of up to 80 characters. rlcuhubm ilons ahidbxonunonheuxudxrcgdp xmkmkmmmmwmwqjbaeeeerceheelciheihcreidercdeehiuhhhn hdcrphdidcrydxgtkdhoendgcidgxfidgfufdgfuuuuuu

public static void randomLines() { Random rand= new Random(); int nl = rand.nextInt(6) + 5; int n; int pos; String letters = "abcdefghijklmnopqrstuvwxyz"; for (int i=0; i<nl; i++) { n = rand.nextInt(80) + 1; for (int j=0; j<n; j++) { pos = rand.nextInt(26); System.out.print(letters.charAt(pos)); } System.out.println(); } }

Write a method named randomWalk that performs a random one-dimensional walk, reporting each position reached and the maximum position reached during the walk. The random walk should begin at position 0. On each step, you should either increase or decrease the position by 1 (with equal probability). The walk stops when 3 or -3 is hit. The output should look like this: position = 0 position = 1 position = 0 position = -1 position = -2 position = -1 position = -2 position = -3 max position = 1

public static void randomWalk() { Random ran = new Random(); int p = 0; int max = 0; System.out.println("position = " + p); while (Math.abs(p) != 3) { int step=ran.nextInt(2); if (step==0) { p++; } else{ p--; } System.out.println("position = " + p); if (p > max) { max = p; } } System.out.println("max position = " + max); }

Write a method named threeHeads that repeatedly flips a coin until three heads in a row are seen. You should use a Random object to give an equal chance to a head or a tail appearing. Each time the coin is flipped, what is seen is displayed (H for heads, T for tails). When 3 heads in a row are flipped a congratulatory message is printed. Here are possible outputs of two calls to threeHeads: T T T H T H H H Three heads in a row!

public static void threeHeads() { Random rand = new Random(); int flip = 0; while (flip < 3) { int n=rand.nextInt(2); if (n==0) { flip++; System.out.print("H"); if (flip != 3) { System.out.print(" "); } } else { flip = 0; System.out.print("T "); } } System.out.println(); System.out.println("Three heads in a row!"); }

Write a method named makeGuesses that will guess numbers between 1 and 50 inclusive until it makes a guess of at least 48. It should report each guess and at the end should report the total number of guesses made. Below is a sample execution: guess = 43 guess = 47 guess = 45 guess = 27 guess = 49 total guesses = 5

public void makeGuesses() { Random rand = new Random(); int n; int count = 0; do { n = rand.nextInt(50) + 1; System.out.println("guess = " + n); count++; } while (n < 48); System.out.println("total guesses = " + count); }

Write a method named printAverage that accepts a Scanner for the console as a parameter and repeatedly prompts the user for numbers. Once any number less than zero is typed, the average of all non-negative numbers typed is displayed. Display the average as a double, and do not round it. For example, a call to your method might look like this: Scanner console = new Scanner(System.in); printAverage(console); The following is one example log of execution for your method: Type a number: 7 Type a number: 4 Type a number: 16 Type a number: -4 Average was 9.0 If the first number typed is negative, do not print an average. For example: Type a number: -2

public void printAverage(Scanner console) { System.out.print("Type a number: "); int x = console.nextInt(); if (x < 0) return; int sum = 0; int n = 0; do { sum += x; n++; System.out.print("Type a number: "); x = console.nextInt(); } while (x >= 0); System.out.println("Average was " + (1.0 * sum/n)); }

Write a method named printFactors that accepts an integer as its parameter and uses a fencepost loop to print the factors of that number, separated by the word " and ". For example, the number 24's factors should print as: 1 and 2 and 3 and 4 and 6 and 8 and 12 and 24 You may assume that the number parameter's value is greater than 0.

public void printFactors(int n) { for (int i=1; i <=n; i++) { if (n % i == 0) { if (i == 1) { System.out.print(i); } else { System.out.print(" and " + i); } } } }

For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false. You may assume that no int values overflow their valid ranges. public static int mystery(Scanner console, int x) { int y = console.nextInt(); int count = 0; // Point A while (y < x) { // Point B if (y == 0) { count++; // Point C } y = console.nextInt(); // Point D } // Point E return count; } Fill in each box of the the table below with ALWAYS, NEVER or SOMETIMES. y < x y == 0 count > 0 Point A Point B Point C Point D Point E

sometimes sometimes never always sometimes sometimes always always always sometimes sometimes sometimes never sometimes sometimes

For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false. public static int mystery(int n) { Random r = new Random(); int a = r.nextInt(3) + 1; int b = 2; // Point A while (n > b) { // Point B b = b + a; if (a > 1) { n--; // Point C a = r.nextInt(b) + 1; } else { a = b + 1; // Point D } } // Point E return n; } Fill in each box of the the table below with ALWAYS, NEVER or SOMETIMES. n > b a > 1 b > a Point A Point B Point C Point D Point E

sometimes sometimes sometimes always sometimes sometimes sometimes always always sometimes always never never sometimes sometimes

Write a do/while loop that repeatedly prints a certain message until the user tells the program to stop. The do/while is appropriate because the message should always be printed at least one time, even if the user types n after the first message appears. The message to be printed is as follows: She sells seashells by the seashore. Do you want to hear it again? y She sells seashells by the seashore. Do you want to hear it again? y She sells seashells by the seashore. Do you want to hear it again? n

Scanner console=new Scanner (System.in); String user; do { System.out.println("She sells seashells by the seashore."); System.out.print("Do you want to hear it again? "); user=console.next(); } while (user.equals("y"));

Write a do/while loop that repeatedly prints random numbers between 0 and 1000 until a number above 900 (that is, greater than or equal to 900) is printed. At least one line of output should always be printed, even if the first random number is above 900. Here is a sample execution: Random number: 235 Random number: 15 Random number: 810 Random number: 147 Random number: 915

Scanner console=new Scanner(System.in); Random rand = new Random(); int n; do { n= rand.nextInt(1000); System.out.println("Random number: " + n); } while (n<900);

Consider the following code. What range of values can each variable (a, b, c, d, and e) have? Specify ranges with a dash i.e. "1 - 10" and separate multiple numbers with commas i.e. "1,2,3,4,5,etc..." Random rand = new Random(); int a = rand.nextInt(100); int b = rand.nextInt(20) + 50; int c = rand.nextInt(20 + 50); int d = rand.nextInt(100) - 20; int e = rand.nextInt(10) * 4;

a. 0-99 b. 50-69 c. 0-69 d. -20-79 e. 0,4,8,12,16,20,24,28,32,36

Given the following method: public static void mystery(int x) { int y = 0; while (x % 2 == 0) { y++; x = x / 2; } System.out.println(x + " " + y); } Write the output of each of the following calls. mystery(19); mystery(42); mystery(48); mystery(40); mystery(64);

mystery(19); 19 0 mystery(42); 21 1 mystery(48); 3 4 mystery(40); 5 3 mystery(64); 1 6

Write a method dominant that accepts three integers as parameters and returns true if any one of the three integers is larger than the sum of the other two integers. The integers might be passed in any order, so the largest value could be any of the three. If no value is larger than the sum of the other two, your method should return false. For example, the call of dominant(4, 9, 2) would return true because 9 is larger than 4 + 2. The call of dominant(5, 3, 7) would return false because none of those three numbers is larger than the sum of the others. You may assume that none of the numbers is negative.

public boolean dominant(int num1,int num2,int num3){ return((num1>(num2+num3)) ||(num2>(num1 +num3)) || (num3 >(num1 + num2))) ; }

Write an expression that generates a random integer between 0 and 10 inclusive. Random rand = new Random(); int n = ???; expression

rand.nextInt(11)

Consider the following variable declarations. Write a new Boolean expression that is the negation of each of the following Boolean expressions. For the longer expressions, use De Morgan's laws rather than simply writing a ! at the beginning of each entire expression. (For Practice-It to accept your solution, your answers should be as similar as possible to the original expressions while changing the various operators between parts of the expression.) b (x > y) && (y > z) (x == y) || (x <= z) (x % 2 != 0) && b (x / 2 == 13) || b || (z * 3 == 96) (z < x) && (z > y || x >= y)

!b (x <= y) || (y < =z) (x != y) && (x > z) (x % 2 == 0)|| !b (x / 2 != 13) && !b && (z * 3 != 96) (z >= x) || (z <= y && x < y)

Consider the following code: Scanner console = new Scanner(System.in); System.out.print("Type something for me! "); if (console.hasNextInt()) { int number = console.nextInt(); System.out.println("Your IQ is " + number); } else if (console.hasNext()) { String token = console.next(); System.out.println("Your name is " + token); } What is the output when the user types the following values? (You don't need to include the "Type something for me!" prompt or the user's input; just write the line of output that would appear after the user is done typing and presses Enter.) Jane 56 56.2

Your name is Jane Your IQ is 56 Your name is 56.2

Using "Boolean Zen," write an improved version of the following method, which returns whether the given number of cents would require any pennies (as opposed to being an amount that could be made exactly using coins other than pennies): (In other words, remove unnecessary logical tests and remove if/else statements that test the value of a boolean variable.) public static boolean hasPennies(int cents) { boolean nickelsOnly = (cents % 5 == 0); if (nickelsOnly == true) { return false; } else { return true; } }

public static boolean hasPennies(int cents) { return (cents % 5 != 0); }

Write a method named swapDigitPairs that accepts an integer n as a parameter and returns a new integer whose value is similar to n's but with each pair of digits swapped in order. For example, the call of swapDigitPairs(482596) would return 845269. Notice that the 9 and 6 are swapped, as are the 2 and 5, and the 4 and 8. If the number contains an odd number of digits, leave the leftmost digit in its original place. For example, the call of swapDigitPairs(1234567) would return 1325476. You should solve this problem without using a String.

public static int swapDigitPairs(int n){ n = Math.abs(n); int count=0; int sum=0; int a; int b; while(n>=10){ a=n%10; n/=10; b=n%10; n/=10; sum+=b*Math.pow(10,count); count++; sum+=a*Math.pow(10,count); count++; } if (n!=0){ sum+=n*Math.pow(10,count); } return sum; }

(This problem is a modified version of Chapter 5's randomX exercise from the textbook.) Write a method named randomX that keeps printing lines, where each line contains a random number of x characters between 5 and 19 inclusive, until it prints a line with 16 or more characters. For example, the output from your method might be the following. Notice that the last line has 17 x characters. xxxxxxx xxxxxxxxxxxxx xxxxxx xxxxxxxxxxx xxxxxxxxxxxxxxxxx

public static void randomX() { Random rand = new Random(); int n; do { n = rand.nextInt(15) + 5; for (int i=0; i< n; i++) { System.out.print("x"); } System.out.println(); } while (n < 16); }

Write a method named showTwos that shows the factors of 2 in a given integer. For example, the following calls: showTwos(7); showTwos(18); showTwos(68); showTwos(120); should produce this output: 7 = 7 18 = 2 * 9 68 = 2 * 2 * 17 120 = 2 * 2 * 2 * 15

public static void showTwos(int n){ System.out.print(n + " = "); while (n % 2 == 0) { System.out.print("2 * "); n /= 2; } System.out.println(n); }

Write code that generates a random odd integer (not divisible by 2) between 50 and 99 inclusive. Fill in the values of the sub-expressions labeled A, B, and C below. Random rand = new Random(); int n = rand.nextInt(A) * B + C; A B C

A 25 B 2 C 51

Write a piece of code that prompts the user for a number and then prints a different message depending on whether the number was an integer or a real number. Here are two sample dialogues: Type a number: 42.5 You typed the real number 42.5 Type a number: 3 You typed the integer 3

Scanner console = new Scanner(System.in); System.out.print("Type a number: "); if (console.hasNextInt()) { int value = console.nextInt(); System.out.println("You typed the integer " + value); } else if (console.hasNextDouble()) { double value = console.nextDouble(); System.out.println("You typed the real number " + value); }

The following code is not robust against invalid user input. Change the code so that it will not proceed until the user has entered a valid age (any integer) and grade point average (GPA, any real number). You may assume that the user enters a single token of input each time when prompted. Here is a sample dialogue of how the code should behave: Type your age: hello Type your age: ? Type your age: 3.14 Type your age: 25 Type your GPA: a Type your GPA: bcd Type your GPA: 2.5 age = 25, GPA = 2.5 Scanner console = new Scanner(System.in); System.out.print("Type your age: "); int age = console.nextInt(); System.out.print("Type your GPA: "); double gpa = console.nextDouble(); System.out.println("age = " + age + ", GPA = " + gpa);

Scanner console = new Scanner(System.in); System.out.print("Type your age: "); while (!console.hasNextInt()) { console.next(); System.out.print("Type your age: "); } int age = console.nextInt(); System.out.print("Type your GPA: "); while (!console.hasNextDouble()) { console.next(); System.out.print("Type your GPA: "); } double gpa = console.nextDouble(); System.out.println("age = " + age + ", GPA = " + gpa);

Write code that prompts for three integers, averages them, and prints the average. Make your code robust against invalid input; if the user types a non-number, re-prompt with the same prompt message. (You may want to look at the getInt method discussed in Chapter 5. You can call that method in your solution if you like.) Here is an example dialogue: Type an integer: 5 Type an integer: 2 Type an integer: 17 Average: 8.0

String prompt = "Type an integer: "; Scanner console = new Scanner(System.in); int num1 = getInt(console, prompt); int num2 = getInt(console, prompt); int num3 = getInt(console, prompt); double average = (num1 + num2 + num3) / 3.0; System.out.println("Average: " + average);

Given the following method: public static void mystery(int x) { int y = 1; int z = 0; while (2 * y <= x) { y = y * 2; z++; } System.out.println(y + " " + z); } Write the output of each of the following calls. mystery(1); mystery(6); mystery(19); mystery(39); mystery(74);

Write the output of each of the following calls. mystery(1); 1 0 mystery(6); 4 2 mystery(19); 16 4 mystery(39); 32 5 mystery(74); 64 6

Given the following variable declarations: int x = 27; int y = -1; int z = 32; boolean b = false; What is the value of each of the following boolean expressions? !b b || true (x > y) && (y > z) (x == y) || (x <= z) !(x % 2 == 0) (x % 2 != 0) && b b && !b b || !b (x < y) == b !(x / 2 == 13) || b || (z * 3 == 96) (z < x) == false !((x > 0) && (y < 0))

true true false true true false false true true true true false

For each of the following do/while loops, how many times will the loop execute its body? Remember that "zero," "infinity," and "unknown" are legal answers. a) int x = 1; do { System.out.print(x + " "); x += 10; } while (x < 100); b) int max = 10; do { System.out.println("count down: " + max); max--; } while (max < 10); c) int x = 250; do { System.out.println(x); } while (x % 3 != 0); d) int x = 100; do { System.out.println(x); x = x / 2; } while (x % 2 == 0); e) int x = 2; do { System.out.print(x + " "); x *= x; } while (x < 200); f) String word = "a"; do { word = "b" + word + "b"; } while (word.length() < 10); System.out.println(word); g) int x = 100; do { System.out.println(x / 10); x = x / 2; } while (x > 0); h) String str = "/\\"; do { str += str; } while (str.length() < 10); System.out.println(str);

a. 10 b. infinity c. infinity d. 2 e. 3 f. 5 g. 7 h. 3

Write a sentinel loop that repeatedly prompts the user to enter a number and, once the number -1 is typed, displays the maximum and minimum numbers that the user entered. Here is a sample dialogue: Type a number (or -1 to stop): 5 Type a number (or -1 to stop): 2 Type a number (or -1 to stop): 17 Type a number (or -1 to stop): 8 Type a number (or -1 to stop): -1 Maximum was 17 Minimum was 2 If -1 is the first number typed, no maximum or minimum should be printed. In this case, the dialogue would look like this: Type a number (or -1 to stop): -1

int SENTINEL = -1; System.out.print("Type a number (or " + SENTINEL + " to stop): "); Scanner console = new Scanner(System.in); int input = console.nextInt(); int min = input; int max = input; while (input != SENTINEL) { if (input < min) { min = input; } else if (input > max) { max = input; } System.out.print("Type a number (or " + SENTINEL + " to stop): "); input = console.nextInt(); } if (min != SENTINEL) { System.out.println("Maximum was " + max); System.out.println("Minimum was " + min); }

Write a method named hopscotch that accepts an integer parameter for a number of "hops" and prints a hopscotch board of that many hops. A "hop" is defined as the split into two numbers and then back together again into one. For example, hopscotch(3); should print: 1 2 3 4 5 6 7 8 9 10

public void hopscotch(int n) { int x=0; for (int i=0; i< n; i++) { System.out.println(" " + (++x)); System.out.println((++x) + " " + (++x)); } System.out.println(" " + (++x)); } 3 spaces

For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false. public static int mystery(Scanner console) { int prev = 0; int count = 0; int next = console.nextInt(); // Point A while (next != 0) { // Point B if (next == prev) { // Point C count++; } prev = next; next = console.nextInt(); // Point D } // Point E return count; } Fill in each box of the the table below with ALWAYS, NEVER or SOMETIMES. next == 0 prev == 0 next == prev Point A Point B Point C Point D Point E

sometimes always sometimes never sometimes sometimes never sometimes sometimes sometimes never always always sometimes sometimes


Conjuntos de estudio relacionados

NUR314 Exam 2 practice questions

View Set

PRACTICE READING Topographic Maps

View Set

Chapter 14 (MANAGEMENT) :leadership

View Set

KIN 245 Chapter 7: The Wrist and Hand Joints

View Set

Critical Reading (Reading Critically)

View Set

6.3.9 Practice Questions Read-Only Domain Controllers (RODCs)

View Set