chapter 4

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

Consider the following Java method, which is written incorrectly. Under what cases will the method print the correct answer, and when will it print an incorrect answer? What should be changed to fix the code? (For an extra challenge, can you think of a way to write the code correctly without any if/else statements?) // This method should return how many of its three // arguments are odd numbers. public static void printNumOdd(int n1, int n2, int n3) { int count = 0; if (n1 % 2 != 0) { count++; } else if (n2 % 2 != 0) { count++; } else if (n3 % 2 != 0) { count++; } System.out.println(count + " of the 3 numbers are odd."); }

// This method should return how many of its three // arguments are odd numbers. public static void printNumOdd(int n1, int n2, int n3) { int count = 0; if (n1 % 2 != 0) { count++; } if (n2 % 2 != 0) { count++; } if (n3 % 2 != 0) { count++; } System.out.println(count + " of the 3 numbers are odd."); } Not else if, just if

Consider the following method. public static void ifElseMystery2(int a, int b) { if (a * 2 < b) { a = a * 3; } if (b < a) { b++; } else { a--; } System.out.println(a + " " + b); } For each call below, indicate what output is produced. ifElseMystery2(10, 2); ifElseMystery2(3, 8); 9 9 ifElseMystery2(4, 4); 3 4 ifElseMystery2(10, 30);

10 3 9 9 3 4 29 30

Consider the following method. public static void ifElseMystery1(int x, int y) { int z = 4; if (z <= x) { z = x + 1; } else { z = z + 9; } if (z <= y) { y++; } System.out.println(z + " " + y); } For each call below, indicate what output is produced. ifElseMystery1(3, 20); ifElseMystery1(4, 5); ifElseMystery1(5, 5); ifElseMystery1(6, 10);

13 21 5 6 6 5 7 11

&& | | ! Can't have

And Or Not true Linked statements 3<x<5 NO

What output is produced by the following program? public class CharMystery { public static void printRange(char startLetter, char endLetter) { for (char letter = startLetter; letter <= endLetter; letter++) { System.out.print(letter); } System.out.println(); } public static void main(String[] args) { printRange('e', 'g'); printRange('n', 's'); printRange('z', 'a'); printRange('q', 'r'); } } printRange('e', 'g'); printRange('n', 's'); printRange('z', 'a'); printRange('q', 'r');

Efg Nopqrs Qr

The expression (0.2 + 1.2 + 2.2 + 3.2) should equal 6.8, but in Java it does not. Why not?

Real numbers are represented as imprecise floating-point numbers in the computer, and the limited precision led to a roundoff error.

The following code contains a logic error. Examine the code and figure out the case(s) in which the code would print something that is untrue about the number that was entered. Then correct the logic error in the code. You should retain the original printed messages (and not add any new ones), but make them print at appropriate times such that the message printed is always a true statement about the integer typed. Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextInt(); if (number % 2 == 0) { if (number % 3 == 0) { System.out.println("Divisible by 6."); } else { System.out.println("Odd."); } }

Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextInt(); if (number % 2 == 0) { if (number % 3 == 0) { System.out.println("Divisible by 6."); } } else { System.out.println("Odd."); } BOTTOM BRACKET IS MOVED

The following code contains a bug. Examine the code and figure out the case(s) in which the code would behave incorrectly. Then correct the bug in the code. Scanner console = new Scanner(System.in); System.out.print("What is your favorite color? "); String name = console.next(); if (name == "blue") { System.out.println("Mine, too!"); }

Scanner console = new Scanner(System.in); System.out.print("What is your favorite color? "); String name = console.next(); if (name.equals("blue")) { System.out.println("Mine, too!"); }

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. The input/output should match the following example: Type a number: 14 even

Scanner console= new Scanner (System.in); System.out.print("Type a number: "); int user=console.nextInt(); if(user % 2 ==0){ System.out.println("even"); } else{ System.out.println("odd"); }

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 "Rank of Suit". You may assume that the user types valid input. Here are two sample executions: Enter a card: 9 S Nine of Spades Enter a card: K C King of Clubs

Scanner console=new Scanner (System.in); System.out.print("Enter a card: "); String rank=console.next(); String suit=console.next(); if (rank.equals("2")) { rank = "Two"; }else if (rank.equals("3")){ rank ="Three"; }else if (rank.equals("A")){ rank ="Ace"; }else if (rank.equals("4")){ rank ="Four"; }else if (rank.equals("5")){ rank ="Five"; }else if (rank.equals("6")){ rank ="Six"; }else if (rank.equals("7")){ rank ="Seven"; }else if (rank.equals("8")){ rank ="Eight"; }else if (rank.equals("9")){ rank ="Nine"; }else if (rank.equals("10")){ rank ="Ten"; }else if (rank.equals("J")){ rank ="Jack"; }else if (rank.equals("K")){ rank ="King"; }else { rank ="Queen"; } if (suit.equals("D")){ suit="Diamonds"; }else if(suit.equals("S")){ suit="Spades"; }else if(suit.equals("C")){ suit="Clubs"; }else { suit="Hearts"; } System.out.print(rank+" of "+suit);

Write code to produce a cumulative product by multiplying together many numbers that are read from the console. Match the following format: How many numbers? 4 Next number --> 7 Next number --> 2 Next number --> 3 Next number --> 15 Product = 630

Scanner console=new Scanner (System.in); System.out.print("How many numbers? "); int number=console.nextInt(); int product=1; for(int i=1;i<=number;i++){ System.out.print("Next number --> "); int user=console.nextInt(); product*=user; } System.out.print("Product = " + product);

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 case-insensitive so that the user can type an uppercase or lowercase letter. Here are two example executions: What color do you want? R You have chosen Red. What color do you want? Bork Unknown color: Bork

Scanner console=new Scanner(System.in); System.out.print("What color do you want? "); String choice=console.next(); if (choice.equalsIgnoreCase("r")) { System.out.println("You have chosen Red."); }else if (choice.equalsIgnoreCase("b")) { System.out.print("You have chosen Blue."); }else if (choice.equalsIgnoreCase("g")) { System.out.print("You have chosen Green."); }else{ System.out.print("Unknown color: " + choice); }

Rewrite the code below by factoring to eliminate redundancy. Your code must produce the same results. To simplify things, you may assume that the user always types 1 or 2 for the multiplier. System.out.print("Is your money multiplied 1 or 2 times? "); int times = console.nextInt(); if (times == 1) { System.out.print("And how much are you contributing? "); int donation = console.nextInt(); sum = sum + donation; count1++; total = total + donation; } if (times == 2) { System.out.print("And how much are you contributing? "); int donation = console.nextInt(); sum = sum + 2 * donation; count2++; total = total + donation; }

System.out.print("Is your money multiplied 1 or 2 times? "); int times = console.nextInt(); System.out.print("And how much are you contributing? "); int donation = console.nextInt(); sum+=times*donation; total += donation; if (times == 1) { count1++; } if (times == 2) { count2++; }

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: public static double getGrade(int percentage) { ... } The grade can be between 0.0 (failing) and 4.0 (perfect). Which of the following are precondition(s) that are appropriate for this method? Check all that apply. (The order of the answer choices is randomly shuffled each time.)

The parameter's value must be less than or equal to 100. The parameter's value must be greater than or equal to 0.

The three types are equilateral, isosceles, and scalene. An equilateral triangle has three sides of the same length, an isosceles triangle has two sides that are the same length, and a scalene triangle has three sides of different lengths. However, certain integer values (or combinations of values) would be illegal and could not represent the sides of an actual triangle. What are these values? (In other words, how would you describe the precondition(s) of the printTriangleType method?)

The three side lengths must be positive integers. No side's length may exceed the sum of any two other side lengths.

Given the following variable declarations: int x = 4; int y = -3; int z = 4; What are the results of the following relational expressions? x == 4 x == y x == z y == z x + y > 0 x - z != 0 y * y <= z y / y == 1 x * (y + 2) > y - (y + z) * 2

True False True False True False False True True

The following code is poorly structured. It contains redundant statements that unnecessarily occur multiple times. Factor out redundant code from the following example by moving it out of the if/else statement, while preserving the same behavior and output. if (x < 30) { a = 2; x++; System.out.println("Java is awesome! " + x); } else { a = 2; System.out.println("Java is awesome! " + x); }

a = 2; if (x < 30) { x++; } System.out.println("Java is awesome! " + x);

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. Fix the code to print the expected message. (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 variable and should still make your test examine that variable's value, rather than just directly testing the gpa variable itself.) double credits = gpa * 3; if (credits == 9.6) { System.out.println("You earned enough credits."); }

double credits = gpa * 3; double diff = Math.abs(credits - 9.6); if (diff < 0.1) { System.out.println("You earned enough credits."); }

Write an if statement that tests to see whether a String stored in a variable named phrase begins with a capital letter. If the string begins with a capital letter, print capital . If not, print not capital . Use at least one method call from the Character class in your solution. You may assume that the string is non-empty (contains at least one character).

if (Character.isUpperCase(phrase.charAt(0))) { System.out.println("capital"); }else{ System.out.println("not capital"); }

Which of the following <code>if</code> statement headers uses the correct syntax?

if (x == y) {

What is wrong with the following code, which attempts to count the number occurrences of the letter 'e' in a string, case-insensitively? Determine what is wrong with the code, and submit a corrected version that works properly. Use at least one method call from the Character class in your solution. int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i).toLowerCase() == 'e') { count++; } }

int count = 0; for (int i = 0; i < s.length(); i++) { if (Character.toLowerCase(s.charAt(i)) == 'e') { count++; } }

The following program contains 7 errors. Correct the errors and submit a working version of the program. The corrected version of the program should produce the following output: a is the smallest! public class Oops4 { public static void main(String[] args) { int a = 7, b = 42; minimum(a, b); if {smaller = a} { System.out.println("a is the smallest!"); } } public static void minimum(int a, int b) { if (a < b) { int smaller = a; } else (a => b) { int smaller = b; } return int smaller; } }

public class Oops4 { public static void main(String[] args) { int a = 7; int b = 42; String smaller=minimum(a, b); System.out.println(smaller+" is the smallest!"); } public static String minimum(int a, int b) { String smaller=""; if (a < b) { smaller = "a"; }else if (a >= b){ smaller = "b"; } return smaller; } }

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 following scale: Score Grade <60 0.0 60-62 0.7 63 0.8 64 0.9 65 1.0 ... 92 3.7 93 3.8 94 3.9 >=95 4.0

public double getGrade(int score) { if (score < 0 || score > 100) { throw new IllegalArgumentException(); } double grade = 0.0; if (score < 60) { grade = 0.0; } else if (score >= 95) { grade = 4.0; } else if (score >= 60 & score <= 62) { grade = 0.7; } else { grade = 0.7 + 0.1* (score - 62); } return grade; }

Write a method named numUnique that takes three integers as parameters and that returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.

public int numUnique(int x, int y, int z) { int n = 3; if (x == y || x == z) { n--; } if (y == z) { n--; } return n; }

Write a method named lastFirst that accepts a string as its parameter representing a person's first and last name. The method should return the person's last name followed by the first initial and a period. For example, the call lastFirst("Marla Singer") should return "Singer, M." . You may assume that the string passed consists of exactly two words separated by a single space.

public static String lastFirst (String name){ int space = name.indexOf(" "); String lastName = name.substring(space + 1); String firstInitial = name.substring(0, 1); String lastNameFirstInitial = lastName + ", " + firstInitial + "."; return lastNameFirstInitial; }

Write a method named 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) returns "hellohellohello". If the number of repetitions is 0 or less, an empty string is returned.

public static String repl(String name, int repititions){ String complete=""; for(int i=1;i<=repititions; i++){ complete+=name; } return complete; }

Write a method named season that takes two integers as parameters representing a month and day and that returns a String indicating 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, and so on) and that the day of the month is a number between 1 and 31. 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 "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, you should return "Fall".

public static String season(int month, int day) { double time = 1.0* month + 0.01*day; String season = ""; if (time >= 12.16 || time <=3.15) { season = "Winter"; } else if (time >= 3.16 && time <= 6.15) { season = "Spring"; } else if (time >= 6.16 && time <= 9.15) { season = "Summer"; } else if (time >=9.16 && time <= 12.15) { season = "Fall"; } return season; }

Write a method called swapPairs that accepts a String as a parameter and returns that String with each pair of adjacent letters reversed. If the String has an odd number of letters, the last letter is unchanged. For example, the call swapPairs("example") should return "xemalpe" and the call swapPairs("hello there") should return "ehll ohtree".

public static String swapPairs(String word) { String res=""; for(int i=0;i<word.length();i++){ if(i%2==0&&i!=word.length()-1){ res+=word.charAt(i+1); }else if (i%2==1&&i!=0){ res+=word.charAt(i-1); } } if (word.length()%2==1){ res+=word.charAt(word.length()-1); } return res; }

Write a method called average that takes two integers as parameters and returns the average of the two integers.

public static double average (int n1, int n2){ double answer=(n1+n2)*.5; return answer; }

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: fraction sum equation In other words, the method should generate the following sequence: 1 + (1/2) + (1/3) + (1/4) + (1/5) + ... You may assume that the parameter n is non-negative.

public static double fractionSum(int n){ double count =0.0; for(int i=1;i<=n;i++){ count +=1.0/i; } return count; }

Write a method named pow2 (a variation of the previous pow exercise) that accepts a real number base and an integer exponent as parameters and returns the base raised to the given power. Your code should work for both positive and negative exponents. For example, the call pow2(2.0, -2) returns 0.25. Do not use Math.pow in your solution.

public static double pow2(double base, int exponent) { if (exponent >0) { double n=1.0; for (int i=1; i<=exponent; i++) { n *= base; } return n; } else if (exponent<0){ double n=1.0; int real=Math.abs(exponent); for (int i=1; i<=real; i++) { n *= base; } double ans=1.0/n; return ans; } else{ return 1.0; } }

Consider the task of writing a method named countFactors that accepts an integer (assumed to be positive) as its parameter and 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) should return 6. The following is an attempt at solving the problem, but it is incorrect. Determine what is wrong with the code, and submit a corrected version that works properly. public static int countFactors(int n) { for (int i = 1; i <= n; i++) { if (n % i == 0) { // a factor return i; } } }

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

Write a method named daysInMonth that accepts 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 (that February always has 28 days).

public static int daysInMonth(int month) { if (month == 2) { return 28; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else { return 31; } }

The following method attempts to return the median (middle) of three integer values, but it contains logic errors. In what cases does the method return an incorrect result? How can the code be fixed? Determine what is wrong with the code, and submit a corrected version that works properly. public static int medianOf3(int n1, int n2, int n3) { if (n1 < n2) { if (n2 < n3) { return n2; } else { return n3; } } else { if (n1 < n3) { return n1; } else { return n3; } } }

public static int medianOf3(int n1, int n2, int n3) { if (n1 < n2 && n1 < n3) { if (n2 < n3) { return n2; } else { return n3; } } else if (n2 < n1 && n2 < n3) { if (n1 < n3) { return n1; } else { return n3; } } else { // (n3 < n1 && n3 < n2) if (n1 < n2) { return n1; } else { return n2; } } } public static int medianOf3(int n1, int n2, int n3) { return Math.max(Math.max(Math.min(n1, n2), Math.min(n2, n3)), Math.min(n1, n3)); }

Write a method named 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) returns 3 * 3 * 3 * 3 or 81. Do not use Math.pow in your solution. Assume that the base and exponent are non-negative.

public static int pow(int base, int exponent){ int value=1; for(int i=0;i<exponent;i++){ value*=base; } return value; }

Write a static method called quadrant that takes as parameters a pair of real numbers representing an (x, y) point and that 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 a counter-clockwise fashion: ^ y-axis | | | Quadrant 2 | Quadrant 1 | <--------------------+--------------------> x-axis | Quadrant 3 | Quadrant 4 | | | V Notice that the quadrant is determined by whether the x and y coordinates are positive or negative numbers. If a point falls on the x-axis or the y-axis, then the method should return 0. Below are sample calls on the method. Call Value Returned quadrant(12.4, 17.8) 1 quadrant(-2.3, 3.5) 2 quadrant(-15.2, -3.1) 3 quadrant(4.5, -42.0) 4 quadrant(0.0, 3.14) 0

public static int quadrant(double x, double y) { if (x == 0.0 || y == 0.0) { return 0; } else if (x > 0) { if (y > 0) { return 1; } else { return 4; } } else { if (y > 0) { return 2; } else { return 3; } } }

Write a method named secondHalfLetters that accepts a string as its parameter and returns an integer representing how many of letters in the string come from the second half of the alphabet (that is, have values of 'n' through 'z' inclusive). Compare case-insensitively, such that uppercase values of 'N' through 'Z' also count. For example, the call secondHalfLetters("ruminates") should return 5 because 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.

public static int secondHalfLetters(String letters){ int count = 0; for (int i = 0; i < letters.length(); i++) { if (Character.toLowerCase(letters.charAt(i)) >= 'n') { count++; } } return count; }

What is wrong with the following sumTo method, which attempts to add all numbers from 1 to a given maximum? Correct the code so 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 value passed is at least 1. public static int sumTo(int n) { for (int i = 1; i <= n; i++) { int sum = 0; sum += i; } return sum; }

public static int sumTo(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; }

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 you?") should return 3, the call wordCount(" this string has wide spaces ") should return 5, and the call wordCount(" ") should return 0.

public static int wordCount(String sentence){ int count=0; sentence=sentence.trim(); if(!sentence.isEmpty()){ for(count=1;sentence.length()>0&& sentence.indexOf(" ")!=-1;count++){ sentence=sentence.substring(sentence.indexOf(" ")); sentence=sentence.trim(); } } return count; }

Write a method named evenSum that prompts the user for many integers and print the total even sum and maximum of the even numbers. You may assume that the user types at least one non-negative even integer. how many integers? 4 next integer? 2 next integer? 9 next integer? 18 next integer? 4 even sum = 24 even max = 18

public static void evenSum(){ Scanner console = new Scanner(System.in); System.out.print("how many integers? "); int n = console.nextInt(); int a=0; int b = 0; int c = 0; for(int i=1;i<=n;i++){ System.out.print("next integer? "); b=console.nextInt(); if(b%2==0){ a+=b; if(b>c) c=b; } } System.out.println("even sum = "+a); System.out.println("even max = "+c); }

Write a static method named longestName that reads names typed by the user and prints the longest name (the name that contains the most characters) in the format shown below. Your method should accept a console Scanner and an integer n as parameters and should then prompt for n names. The longest name should be printed with its first letter capitalized and all subsequent letters in lowercase, regardless of the capitalization the user used when typing in the name. If there is a tie for longest between two or more names, use the tied name that was typed earliest. Also print a message saying that there was a tie, as in the right log below. It's possible that some shorter names will tie in length, such as DANE and Erik in the left log below; but don't print a message unless the tie is between the longest names. You may assume that n is at least 1, that each name is at least 1 character long, and that the user will type single-word names consisting of only letters. The following table shows two sample calls and their output: Call Scanner console = new Scanner(System.in); longestName(console, 5); Scanner console = new Scanner(System.in); longestName(console, 7); Output name #1? roy name #2? DANE name #3? Erik name #4? sTeFaNiE name #5? LaurA Stefanie's name is longest name #1? TrEnt name #2? rita name #3? JORDAN name #4? craig name #5? leslie name #6? YUKI name #7? TaNnEr Jordan's name is longest (There was a tie!)

public static void longestName(Scanner console, int size){ String longest =""; int count=0; for(int i=1;i<=size;i++){ System.out.print("name #"+i+"? "); String name=console.next().toLowerCase(); if(name.length()==longest.length()){ count++; } else if(name.length()>longest.length()){ longest=name; count=1; } } System.out.println(longest.substring(0,1).toUpperCase()+longest.substring(1)+"'s name is longest"); if(count>1){ System.out.println("(There was a tie!)"); } }

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). 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 integer max as an argument and prints out all perfect numbers that are less than or equal to max. Here is the console output from a call to perfectNumbers(6): Perfect numbers up to 6: 6 Here is the console output from a call to perfectNumbers(500): Perfect numbers up to 500: 6 28 496

public static void perfectNumbers(int num){ System.out.print("Perfect numbers up to " + num + ":"); int sumFactor=0; for(int i=2;i<=num;i++){ sumFactor=0; for(int j=1;j<i;j++){ if(i%j==0){ sumFactor+=j; } } if(sumFactor==i){ System.out.print(" "+i); } } }

Write a method named printGPA that calculates a student's grade point average. The user will type a line of input containing the student's name, then a number of scores, followed by that many integer scores. Here are two example dialogues: Enter a student record: Maria 5 72 91 84 89 78 Maria's grade is 82.8 Enter a student record: Jordan 4 86 71 62 90 Jordan's grade is 77.25 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.

public static void printGPA(){ Scanner console=new Scanner (System.in); System.out.print("Enter a student record: "); String name = console.next(); int n = console.nextInt(); int sum = 0; for (int i=0; i<n; i++) { sum += console.nextInt(); } double grade = 1.0 * sum / n; System.out.println(name + "'s grade is " + grade); }

Write a method called printPalindrome that accepts a Scanner for the console as a parameter, and prompts the user to enter one or more words and prints whether the entered String is a palindrome (i.e., reads the same forwards as it does backwards, like "abba" or "racecar"). If the following Scanner object were declared: Scanner console = new Scanner(System.in); printPalindrome(console); The resulting output for a call where the user types a palindrome would be: Type one or more words: racecar racecar is a palindrome! The output for a call where the user types a word that is not a palindrome would be: Type one or more words: hello hello is not a palindrome.

public static void printPalindrome(Scanner console) { System.out.print("Type one or more words: "); String word = console.next(); String comp=""; String word2=word.toLowerCase(); for(int i=word2.length()-1;i>=0;i--){ comp+=word2.charAt(i); } System.out.println(); if(comp.equals(word2)){ System.out.println( word + " is a palindrome!"); }else{ System.out.println(word + " is not a palindrome."); } }

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 the same, that number should be printed by itself. Here are some sample calls to printRange: printRange(2, 7); printRange(19, 11); printRange(5, 5); The output produced should be the following: 2 3 4 5 6 7 19 18 17 16 15 14 13 12 11 5

public static void printRange(int a, int b) { if (a < b) { for (int i=a; i<=b; i++) { System.out.print(i + " "); } } else { for (int i=a; i>=b; i--) { System.out.print(i + " "); } } }

Write a method named smallestLargest that asks the user to enter numbers, then prints the smallest and largest of all the numbers 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 example dialogue: How many numbers do you want to enter? 4 Number 1: 5 Number 2: 11 Number 3: -2 Number 4: 3 Smallest = -2 Largest = 11

public static void smallestLargest(){ Scanner console=new Scanner (System.in); System.out.print("How many numbers do you want to enter? "); int number=console.nextInt(); int a =0; int s =1000; for(int i=1;i<=number;i++){ int ans=0; System.out.print("Number "+i+": "); ans=console.nextInt(); if(ans>a) a=ans; if (ans<s) s=ans; } System.out.println("Smallest = "+s); System.out.println("Largest = "+a); }

The following code is poorly structured. Rewrite it so that it has a better structure and avoids redundancy. To help eliminate redundancy, convert the code into a method named spending that accepts two parameters: a Scanner for the console, and a String for a single person's name, and prints the appropriate information about that person's bills. Your method could be called twice (once for John and once for Jane) to replicate the original code's behavior. Scanner console = new Scanner(System.in); System.out.print("How much will John be spending? "); double amount = console.nextDouble(); System.out.println(); int numBills1 = (int) (amount / 20.0); if (numBills1 * 20.0 < amount) { numBills1++; } System.out.print("How much will Jane be spending? "); amount = console.nextDouble(); System.out.println(); int numBills2 = (int) (amount / 20.0); if (numBills2 * 20.0 < amount) { numBills2++; } System.out.println("John needs " + numBills1 + " bills"); System.out.println("Jane needs " + numBills2 + " bills");

public static void spending(Scanner console, String name) { System.out.print("How much will " + name + " be spending? "); double amount = console.nextDouble(); System.out.println(); int spend = (int) (amount / 20.0); if (spend * 20.0 < amount) { spend++; } System.out.print(name+" needs " + spend+" bills"); }

Write a static method named 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. In other words, on the first line, the first and last characters are "x"; on the second line, the second and second-from-last characters are "x"; and so on. If 0 or less is passed for the size, no output should be produced. The following table lists some calls to your method and their expected output: Call xo(5); xo(8); xo(3); xo(1); xo(0); xo(12); xo(11);

public static void xo (int size){ for(int rows=1;rows<=size;rows++){ for(int cols=1;cols<=size;cols++){ if (rows==cols){ System.out.print("x"); }else if (cols==size-rows+1){ System.out.print("x"); }else{ System.out.print("o"); } } System.out.println(); } }

Write a method called printTriangleType that accepts three integer arguments representing the lengths of the sides of a triangle and prints what type of triangle it is. The three types are equilateral, isosceles, and scalene. An equilateral triangle has all three sides the same length, an isosceles triangle has two sides the same length, and a scalene triangle has three sides of different lengths. Here are some example calls to printTriangleType: printTriangleType(5, 7, 7); printTriangleType(6, 6, 6); printTriangleType(5, 7, 8); printTriangleType(12, 18, 12); The output produced should be the following: isosceles equilateral scalene isosceles

public void printTriangleType(int a, int b, int c) { if (a == b && b == c) { System.out.println("equilateral"); } else if ( a == b || b == c || a == c) { System.out.println("isosceles"); } else { System.out.println("scalene"); } }

Translate each of the following English statements into logical tests that could be used in an if/else statement. Write the appropriate logical test for each statement below. Assume that three int variables, x, y, and z, have already been declared. a. z is odd. b. z is not greater than y's square root. c. y is positive. d. Either x or y is even, and the other is odd. (Hint: Don't use && or ||.) e. y is a multiple of z. f. z is not zero. g. y is greater in magnitude than z. h. x and z are of opposite signs. i. y is a nonnegative one-digit number. j. z is nonnegative. k. x is even l. x is closer in value to y than z is.

z%2==1 !(z>Math.sqrt(y)) y>0 x % 2 != y % 2 y % z == 0 z !=0 Math.abs(y)>Math.abs(z) (x >= 0) == (z < 0) y % 10 == y z>=0 x%2==0 Math.abs(x - y) < Math.abs(z - y)


Conjuntos de estudio relacionados

Internet-Based research SBE CITI

View Set

history unit 2 actual review guide

View Set

Chapter 1: Responsibilities for Care in Community/Public Health Nursing

View Set

Retirement Planning and Employee Benefits - Employer/Employee Insurance Arrangements

View Set

Chapter 31: The Child with Musculoskeletal or Articular Dysfunction

View Set