Java Programming Tutorial 1: Hello World

Ace your homework & exams now with Quizwiz!

This method should return how many of its three // arguments are odd numbers.

// 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."); }

What is the result of the following expression? Note that x is used as the multiply symbol instead of the asterisk. (because of quizlet formatting the asterisk becomes *bold* much like commenting with slash asterik) 1 + 2 x 3 + 7 * 2 % 5

11

Write 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 b){ b = b.toLowerCase(); return b.equals("a") || b.equals("e") || b.equals("i") || b.equals("o") || b.equals("u"); }

Write a method called scientific that accepts two real numbers as parameters for a base and an exponent and computes the base times 10 to the exponent, as seen in scientific notation. For example, the call of scientific(6.23, 5.0) would return 623000.0 and the call of scientific(1.9, -2.0) would return 0.019.

public static double scientific(double b, int b1){ return b * Math.pow(10, b1); }

Write a method named 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.

public static int lastDigit(int b){ return Math.abs(b % 10); }

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);

1 0 4 2 16 4 32 5 64 6

Arrays.toString format example: [0, 0, 0] The following program produces 3 lines of output. Write each line of output below as it would appear on the console. import java.util.*; public class ReferenceMystery { public static void main(String[] args) { int x = 4; int y = 8; int[] data = {5, 10, 15}; x = mystery1(y, data); System.out.println(y + " " + Arrays.toString(data)); mystery2(x, y); System.out.println(x + " " + y); } public static int mystery1(int n, int[] numbers) { n = n + 100; numbers[2]--; System.out.println(n + " " + Arrays.toString(numbers)); return numbers[1] * 2; } public static void mystery2(int x, int y) { x++; y = y * 3; } }

108 [5, 10, 14] 8 [5, 10, 14] 20 8

Write a method called vertical that accepts a String as its parameter and prints each letter of the string on separate lines.

public static void vertical(String b){ for(int i = 0; i < b.length(); i++){ System.out.println(b.charAt(i) + ""); } }

Write a for loop that produces the following output: 10 bottles of beer on the wall, 10 bottles of beer Take one down, pass it around, 9 bottles of beer on the wall 9 bottles of beer on the wall, 9 bottles of beer Take one down, pass it around, 8 bottles of beer on the wall ... (output continues in the same pattern) ... 1 bottles of beer on the wall, 1 bottles of beer Take one down, pass it around, 0 bottles of beer on the wall

for(int i = 10; i > 0; i--){ System.out.println(i + " bottles of beer on the wall, " + i + " bottles of beer"); System.out.println("Take one down, pass it around, " + (i-1) + " bottles of beer on the wall"); System.out.println(); }

Which of the following if statement headers uses the correct syntax? if x = 10 then { if (x equals 42) { if [x == 10] { if (x == y) { if (x => y) {

if (x == y) {

Which of the following choices is the correct syntax for declaring/initializing an array of ten integers? int[] a = new int[10]; int a[10]; int[10] a = new int[10]; int a[10] = new int[10]; []int a = [10]int;

int[] a = new int[10];

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:

public static void smallestLargest(){ Scanner b = new Scanner(System.in); System.out.print("How many numbers do you want to enter? "); int b1 = b.nextInt(); int b3 = 100000; int b4 = -100000; for(int i = 0; i < b1; i++){ System.out.print("Number " + (i + 1) + ": "); int i2 = b.nextInt(); if(i2 > b4){ b4 = i2; } if(i2 < b3){ b3 = i2; } } System.out.println("Smallest = " + b3); System.out.println("Largest = " + b4); }

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.

public static int largerAbsVal(int a, int b){ return Math.max(Math.abs(a), Math.abs(b)); }

Write a method named showTwos that shows the factors of 2 in a given integer.

public static void showTwos(int n) { System.out.print(n + " = "); int b = 1; int a = countFactors2(Math.abs(n)); for (int i = 0; i < a; i++) { System.out.print("2 * "); b++; } int ab = n; for(int i = 0; i < a; i++){ ab = ab / 2; } //((int)Math.pow(2, a)) = n //2^a * remainder //System.out.println( log2 (n)); System.out.println(ab); } public static int countFactors(int n) { int b = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { // a factor b++; } } return b; } public static int countFactors2(int n) { int b = 0; for (int i = 2; i <= n; i *= 2) { if (n % i == 0) { // a factor b++; } } return b; }

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.

public static void xo(int b){ if(b == 0){ return; } if(b == 1){ System.out.print("x"); return; } for(int i = 0; i < b / 2; i++){ for(int b1 = 0; b1 <= (-1 + i); b1++){ System.out.print("o"); } System.out.print("x"); for(int b1 = 0; b1 < (b - 2) - (2*i); b1++){ System.out.print("o"); } System.out.print("x"); for(int b1 = 0; b1 <= (-1 + i); b1++){ System.out.print("o"); } System.out.println(); } for(int i = b / 2; i < b; i++){ for(int b2 = 0; b2 < (b - 1) - (i); b2++){ System.out.print("o"); } System.out.print("x"); for(int b2 = 0; b2 < (-(b) + (2 * i)); b2++){ System.out.print("o"); } if(b % 2 == 1 && i == b / 2){ }else{ System.out.print("x"); } for(int b2 = 0; b2 < (b - 1) - (i); b2++){ System.out.print("o"); } System.out.println(); } }

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

public static double average(int b, int b1){ double sum = b + b1 + 0.0; return sum / 2.0; }

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:

public static void hopscotch(int j){ int count = 0; for(int i = 0; i < (3 * j) + 1; i++){ if(count % 2 == 0){ System.out.println(" " + (i + 1)); }else{ System.out.println((i+1) + " " + (i+2)); i++; } count++; } }

Write a method called printPowersOf2 that accepts a maximum number as an argument and prints each power of 2 from 20 (1) up to that maximum power, inclusive. For example, consider the following calls: printPowersOf2(3); printPowersOf2(10); You may assume that the value passed to printPowersOf2 is 0 or greater. (The Math class may help you with this problem. If you use it, you may need to cast its results from double to int so that you don't see a .0 after each number in your output. Also, can you write this program without using the Math class?)

public static void printPowersOf2(int x){ System.out.print("1 "); int prev = 1; for(int i = 1; i <= x; i++){ System.out.print(((2)* prev) + " "); prev = 2 * prev; } System.out.println(); }

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:

public static void threeHeads(){ int row = 1; Random r = new Random(); int prev = 0; while(row < 4){ int x = r.nextInt(2); if(x == 0){ System.out.print("H "); }else{ System.out.print("T "); } if(x == 0){ if(x == prev){ row++; }else{ row = 0; } }else{ row = 0; } prev = x; } System.out.println("\nThree heads in a row!"); }

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 b, int b1){ int b0 = 1; if(b1 == 0){ return 1; } if(b1 == 1){ return b; } for(int i = 0; i < b1; i++){ b0 *= b; } return b0; }

Write a method named area that accepts the radius of a circle as a parameter and returns the area of a circle with that radius. For example, the call area(2.0) should return 12.566370614359172. You may assume that the radius is non-negative.

public static double area(double b){ return Math.PI * Math.pow(b, 2); }

Write a method largestAbsVal that accepts 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.

public static int largestAbsVal(int a, int b, int c){ int max = Math.max(Math.abs(a), Math.abs(b)); return Math.max(max, Math.abs(c)); }

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 if(n2 == n3){ return (n1 + n2 + n3) / 3; } else if(n3 < n1){ return n1; }else{ return n3; } } else { if (n1 < n3) { return n1; } else if(n2 == n3){ return (n1 + n2 + n3) / 3; } else if(n3 < n2){ return n2; }else{ return n3; } } }

Write a static method called reportScore that takes as a parameter a Scanner containing information about a student's performance and that prints a report for that student. Students are given gold stars for tasks they solved particularly well and minuses for tasks where they performed poorly. The information for each student is presented as a series of count/type pairs where each count is a positive integer and each type is either "*" or "-". These count/type pairs are followed by the student's name which is guaranteed to be a single word composed entirely of alphabetic characters. You may not construct any extra data structures to solve this problem.

public static void reportScore(Scanner s){ int gold = 0; int minus = 0; String name = ""; int storage = 0; while(s.hasNext()){ if(s.hasNextInt()){ int x = s.nextInt(); storage = x; }else{ String str = s.next(); if(str.length() > 1){ name = str; }else{ if(str.equals("*")){ gold += storage; }else{ minus += storage; } } } } int tally = gold - minus; int total = gold + minus; System.out.println(name + " got " + tally + " of " + total); }

Write a static method called reverseAndFlip that takes a Scanner containing an input file as a parameter and that writes to System.out the same file with successive pairs of lines reversed in order and with the second line of each pair reversed. The method switches the order of the first two lines, printing the second line reversed. Then it switches the order of the third and fourth lines, print the fourth line reversed.

public static void reverseAndFlip(Scanner s){ int x = -1; String storage = ""; while(s.hasNextLine()){ String str = s.nextLine(); String str2 = ""; if(!str.equals("")){ x++; if(x % 2 == 0){ storage = str; } if(x % 2 == 1){ for(int i = 0; i < str.length(); i++){ char c = str.charAt(str.length() - 1 - i); str2 += "" + c; } System.out.println(str2); System.out.println(storage); storage = ""; } }else{ x--; storage = ""; } if(x == 6){ System.out.println(str); } } }

Write a method named sequenceSum that prints terms of the following mathematical sequence: Your method should accept a real number as a parameter representing a limit, and should add and print terms of the sequence until the sum of terms meets or exceeds that limit. For example, if your method is passed 2.0, print terms until the sum of those terms is at >= 2.0. You should round your answer to 3 digits past the decimal point. The following is the output from the call sequenceSum(2.0); 1 + 1/2 + 1/3 + 1/4 = 2.083 (Despite the fact that the terms keep getting smaller, the sequence can actually produce an arbitrarily large sum if enough terms are added.) If your method is passed a value less than 1.0, no output should be produced. You must match the output format shown exactly; note the spaces and pluses separating neighboring terms.

public static void sequenceSum(double limit) { if (limit >= 1) { System.out.print("1"); int denomenator = 1; double sum = 1.0; while (sum < limit) { denomenator++; sum += 1.0 / denomenator; System.out.print(" + 1/" + denomenator); } System.out.println(" = " + sum); } }

Given an array of scores, return true if there are scores of 100 next to each other in the array. The array length will be at least 2. scores100([1, 100, 100]) → truescores100([1, 100, 99, 100]) → falsescores100([100, 1, 100, 100]) → true

public boolean scores100(int[] scores) { int storage = scores[0]; for(int i = 1; i < scores.length; i++){ int stor = scores[i]; if(stor == storage){ return true; } storage = stor; } return false; }

Given an array of scores, return true if each score is equal or greater than the one before. The array will be length 2 or more. scoresIncreasing([1, 3, 4]) → truescoresIncreasing([1, 3, 2]) → falsescoresIncreasing([1, 1, 4]) → true

public boolean scoresIncreasing(int[] scores) { int first = scores[0]; for(int a = 1; a < scores.length; a++){ if(scores[a] < first){ return false; } first = scores[a]; } return true; }

Write a complete program called "TheNameGame", where the user inputs a first and last name and a song in the following format is printed about their first, then last, name. Use a method to avoid redundancy.

public class TheNameGame{ public static void main(String[] args){ Scanner s = new Scanner(System.in); System.out.print("What is your name? "); String str = s.nextLine(); Scanner s2 = new Scanner(str); while(s2.hasNext()){ String str1 = s2.next(); System.out.println(str1 + " " + str1 + ", bo-B" + str1.substring(1)); System.out.println("Banana-fana fo-F" + str1.substring(1)); System.out.println("Fee-fi-mo-M" + str1.substring(1)); System.out.println(str1.toUpperCase() + "!"); System.out.println(); } } }

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 b1){ int b2 = b1.indexOf(" "); String b3 = b1.substring(b2 + 1); String b4 = b1.substring(0, b2); return b3 + ", " + b4.charAt(0) + "."; }

Write a method 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 trying to print output that lines up horizontally.) If the string's length is already at least as long as the length parameter, your method should return the original string. For example, padString("congratulations", 10) would return "congratulations".

public static String padString(String str, int b){ if(str.length() >= b){ return str; } int b1 = b - str.length(); for(int i = 0; i < b1; i++){ str = " " + str; } return str; }

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 b, int b1){ String b2 = ""; for(int i = 0; i < b1; i++){ b2 += b; } return b2; }

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 m, int d){ if(m < 3){ return "Winter"; } if(m == 3 && d <= 15){ return "Winter"; } if(m < 6){ return "Spring"; } if(m == 6 && d <= 15){ return "Spring"; } if(m < 9){ return "Summer"; } if(m == 9 && d <= 15){ return "Summer"; } if(m < 12){ return "Fall"; } if(m == 12 && d <= 15){ return "Fall"; } return "Winter"; }

Write a method called stutter that accepts a parameter and returns the String with its characters returns repeated twice. For example, stutter("Hello!") returns "HHeelllloo!!"

public static String stutter(String b){ String a = ""; for(int i = 0; i < b.length(); i++){ a += b.charAt(i); a += b.charAt(i); } return a; }

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.

public static boolean allDigitsOdd(int ab){ int b1 = 0; int originalab = ab; boolean b = true; int i = 0; if(ab < 0){ return allDigitsOdd(ab / -1); } if(ab < 10){ return (ab % 2 == 1); } while(b){ int reallylastdigit = lastDigit(ab); if(ab == 0){ b = false; }else{ if(reallylastdigit % 2 == 0){ return false; } } if(ab == 0){ b = false; } ab = ab/ 10; } return true; } public static int lastDigit(int number){ if(number < 0){ number = number / -1; } return number % 10; }

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.

public static boolean anglePairs(int a, int b, int ab){ if(a == b || a == ab || b == ab){ int c = largestAbsVal(a, b, ab); return (c < 180 && c > 90); } if(ab > a && ab > b){ return a + b == 90; } if(a > ab && a > b){ return ab + b == 90; } return ab + a == 90; } public static int largestAbsVal(int a, int b, int c){ int max = Math.max(Math.abs(a), Math.abs(b)); return Math.max(max, Math.abs(c)); }

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 static int numUnique(int a, int a1, int b){ int b1 = 3; if(a == a1){ b1--; } if(a == b || b == a1){ b1--; } return b1; }

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 ab){ int c = Math.abs(a - b); int c1 = Math.abs(a - ab); int c0 = Math.abs(b - ab); int d = c + c1 + c0; if(c == 0){ return false; } return d == 3 || d == 4; }

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 static boolean dominant(int a, int b, int ab){ int b1 = largestAbsVal(a, b, ab); if(b1 > a && b1 > b){ return b1 > (a + b); } if(b1 > a && b1 > ab){ return b1 > (a + ab); } return b1 > (b + ab); } public static int largestAbsVal(int a, int b, int c){ int max = Math.max(Math.abs(a), Math.abs(b)); return Math.max(max, Math.abs(c)); }

Write a method named hasAnOddDigit that returns whether any digit of an 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.

public static boolean hasAnOddDigit(int ab){ int b1 = 0; int originalab = ab; boolean b = true; int i = 0; if(ab < 0){ return hasAnOddDigit(ab / -1); } if(ab < 10){ return (ab % 2 == 1); } while(b){ int reallylastdigit = lastDigit(ab); if(ab == 0){ b = false; }else{ if(reallylastdigit % 2 == 1){ return true; } } if(ab == 0){ b = false; } ab = ab/ 10; } return false; } public static int lastDigit(int number){ if(number < 0){ number = number / -1; } return number % 10; }

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 a, int b, int ab){ int c = Math.abs(a - b); int c1 = Math.abs(a - ab); int c0 = Math.abs(b - ab); int ab1 = 0; if(c == c0){ ab1++; } if(c1 == c0){ ab1++; } if(c == c1){ ab1++; } return ab1 == 1 || ab1 == 3; }

Write a method highLow that accepts an integer as a parameter and returns whether or not the number has alternating "high" and "low" digits. 0 through 4 are "low" digits and 5 through 9 are "high" digits. Your method should return true if the number passed alternates between "high" and "low" digits, and false if not. You may assume the number passed is positive. If the number passed consists of a single digit, your method should return true. Note: The method returns true if the number alternates starting with a "high" digit or starting with a "low" digit. What is important is that the digits alternate. For example, both highLow(9292) and highLow(2929) should return true.

public static boolean highLow(int number) { int digit = number % 10; number = number / 10; boolean lookForHigh = (digit < 5); while (number != 0) { digit = number % 10; number = number / 10; if (lookForHigh && (digit >= 5)) { lookForHigh = false; } else if (!lookForHigh && (digit < 5)) { lookForHigh = true; } else { return false; } } return true; } public static boolean highLow(int n) { int prev = 3; // 3 to start; then 1 for 'low' and 2 for 'high' while (n != 0) { int curr; if (n % 10 <= 4) { curr = 1; } else { curr = 2; } if (prev == curr) { return false; } n /= 10; prev = curr; } return true; } public static boolean highLow(int n) { while (n != 0) { int digit = n % 10; n = n / 10; if (digit <= 4 && n > 0 && n % 10 <= 4) { return false; } if (digit >= 5 && n > 0 && n % 10 >= 5) { return false; } } return true; }

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.

public static boolean isAllVowels(String str){ // do not use advanced material //char[] array = str.toCharArray(); for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); boolean b = isVowel(c + ""); if(b == false){ return false; } } return true; } public static boolean isVowel(String b){ b = b.toLowerCase(); return b.equals("a") || b.equals("e") || b.equals("i") || b.equals("o") || b.equals("u"); }

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 = false; for (int i = 2; i < n; i++) { if (n % i == 0) { prime = true; } } return !prime; }

Write a method called numWords that takes a String as a parameter and that returns the number of words in the String. By definition, words are separated by one or more spaces. Notice that words can contain punctuation marks. Any non-empty sequence of non-space characters can be a word. Also notice that there might be spaces at the beginning or end of the String. You may not construct any other objects to solve this problem (e.g., you can't use a Scanner or tokenizer). You may assume that the String has no other whitespace characters such as tabs or newline characters. Your method can pay attention just to spaces to decide how many words there are.

public static int numWords(String s) { int count = 0; boolean inWord = false; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ' ') { inWord = false; } else if (!inWord) { count++; inWord = true; } } return count; }

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.

public static boolean monthApart(int a, int b, int ab, int ab0){ int ac = daysInMonth(a); int abc = daysInMonth(ab); if(a > ab){ int c = a - ab; if(c == 1){ if(abc == 30){ if(b == ab0){ return true; } } }else{ return true; } return ab0 < b; } if(ab > a){ int c = ab - a; if(c == 1){ if(ac == 30){ if(b == ab0){ return true; } } }else{ return true; } return b < ab0; } return false; } public static int daysInMonth(int i){ if(i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12){ return 31; }else if(i == 4 || i == 6 || i == 9 || i == 11){ return 30; }else{ return 28; } }

Write a method sameDashes that takes two Strings as parameters and that returns whether or not they have dashes in the same places (returning true if they do and returning false otherwise). For example, below are four pairs of Strings of equal length that have the same pattern of dashes. Notice that the last pair has no dashes at all. string 1: "hi--there-you." "-15-389" "criminal-plan" "abc" string 2: "12--(134)-7539" "-xy-zzy" "(206)555-1384" "9.8" To be considered a match, the Strings must have exactly the same number of dashes in exactly the same positions. The Strings might be of different length. For example, the following calls should each return true: sameDashes("1st-has-more characters", "2nd-has-less") sameDashes("1st-has-less", "2nd-has-more characters") because the Strings each have two dashes and they are in the same positions. But the following calls should each return false because the longer string has a third dash where the shorter string does not: sameDashes("1st-has-more-characters", "2nd-has-less") sameDashes("1st-has-less", "2nd-has-more-characters")

public static boolean sameDashes(String str, String str2){ boolean zig = true; int tally = 0; int short1 = Math.min(str.length(), str2.length()); for(int i = 0; i < short1; i++){ char c1 = str.charAt(i); char c2 = str2.charAt(i); if(c1 == c2){ if(c1 == '-'){ tally++; } } else if(c1 == '-' || c2 == '-'){ zig = false; } } if(str.length() > str2.length()){ int short2 = str2.length(); int diff = str.length() - str2.length(); for(int i = 0; i < diff; i++){ char c0 = str.charAt(short2 + i); if (c0 == '-'){ return false; } } } if(str2.length() > str.length()){ int short2 = str.length(); int diff = str2.length() - str.length(); for(int i = 0; i < diff; i++){ char c0 = str2.charAt(short2 + i); if (c0 == '-'){ return false; } } } return zig; }

Write a method called cylinderSurfaceArea that accepts a radius and height (both real numbers) 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.

public static double cylinderSurfaceArea(double b, double b1){ return (2 * Math.PI * Math.pow(b, 2)) + (2 * Math.PI * b * b1); }

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. For example, the call of distance(1, 0, 4, 4) would return 5.0 and the call of distance(10, 2, 3, 5) would return 7.615773105863909.

public static double distance(int b, int b2, int b1, int b3){ double b4 = Math.pow(b1 - b, 2); double b5 = Math.pow(b3 - b2, 2); double b6 = b4 + b5; double b31 = Math.sqrt(b6); return b31; }

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: 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 b = 0; for(int i = 0; i < n; i++){ b += (double)(1 / (double)(1 + i)); } return b; }

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).

public static double getGrade(int b){ if(b < 0 || b > 100){ throw new IllegalArgumentException(); }else if(b > 95){ return 4.0; }else if(b < 60){ return 0.0; }else if(b < 63){ return 0.7; } return 0.8 + (0.1 * (b - 63)); }

Write a method named pay that accepts a real number for a TA's salary and an integer for the number of hours the TA worked this week, and returns how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. The TA should receive "overtime" pay of 1 ½ normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0.

public static double pay(double b, int b1){ int b2 = 0; if(b1 > 8){ b2 = b1 - 8; return b * 8 + (b2 * 1.5 * b); } return b * b1; }

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 b, int b1){ if(b1 < 0){ double b2 = 1.0; for(int b4 = 0; b4 < (-1 * b1); b4++){ b2 = b2 * b; } return 1/b2; } double b5 = Math.floor(b); int b6 = (int)Math.floor(b1); if(b5 != b){ double b0 = 1.0; for(int i = 0; i < b1; i++){ b0 *= b; } return b0; } int b8 = 1; if(b1 == 0){ return 1; } if(b1 == 1){ return b; } for(int i = 0; i < b1; i++){ b8 *= b; } return b8; }

Write a method called sphereVolume that accepts a radius (a real number) as a parameter and returns the volume of a sphere with that radius. For example, the call sphereVolume(2.0) should return 33.510321638291124.

public static double sphereVolume(double b){ return (4.0/3.0) * Math.PI * (Math.pow(b, 3)); }

Write a method called triangleArea that accepts the three side lengths of a triangle (all real numbers) 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 that the area of a triangle whose three sides have lengths a, b, and c, is the following.

public static double triangleArea(double b1, double b2, double b3){ double b = (b1 + b2 + b3)/2; double b4 = Math.sqrt((b * (b - b1) * (b - b2) * (b - b3))); return b4; }

Write a static method named baseball that takes a Scanner representing the console as a parameter and plays an interactive baseball scoring game with the user, returning an integer representing which team won the game. Baseball is a sport where teams play a series of innings against each other. Each team scores a certain number of runs (points) in each inning. A baseball game ends when one of the following conditions is met: After 9 innings are finished, if one team has more total runs than the other, the team with more runs wins. After 9 innings are finished, if the teams are tied (if they have the same number of total runs), we keep playing one more full inning at a time until the teams are not tied any more. After any inning, if one team is ahead by 10 or more runs, the game is called and the team with more runs wins. Your method should repeatedly prompt the user, once per inning, to enter the number of runs that each team scored during each inning. The user will type in the first team's runs for that inning, followed by the second team's runs for that inning, separated by whitespace. Your method should stop prompting once one or more of the above bulleted conditions are met, causing the game to end. At the end of the game, you should print the final score. You should also return an integer for which team won: return 1 if the first team won, and 2 if the second team won. You may assume that the user enters valid non-negative integers whenever prompted, and you may assume that the game will eventually end (it won't go on forever).

public static int baseball(Scanner console) { int score1 = 0; int score2 = 0; int inning = 1; while ((inning <= 9 || score1 == score2) && Math.abs(score1 - score2) < 10) { System.out.print("Inning #" + inning + ": "); score1 += console.nextInt(); score2 += console.nextInt(); inning++; } System.out.println("Final score: " + score1 + " - " + score2); if (score1 > score2) { return 1; } else { return 2; } }

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.

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

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 i){ if(i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12){ return 31; }else if(i == 4 || i == 6 || i == 9 || i == 11){ return 30; }else{ return 28; } }

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 static int digitRange(int b){ if(b < -9){ return digitRange(Math.abs(b)); }if(b < 10){ return 1; } int first = firstDigit(b); int last = lastDigit(b); int sum = digitSum(b); int biggest = 0; int smallest = 0; if(b < 100 && b >= 10){ biggest = Math.max(first, last); smallest = Math.min(first, last); return biggest - smallest + 1; } if(b < 1000 && b >= 100){ int diff = sum - last - first; biggest = largestAbsVal(diff, first, last); smallest = smallestAbsVal(diff, first, last); return biggest - smallest + 1; } if(b < 10000 && b >= 1000){ int last2 = lastDigit(b/10); int last3 = lastDigit(b/100); biggest = largestAbsVal4(last3, first, last, last2); smallest = smallestAbsVal4(last3, first, last, last2); return biggest - smallest + 1; } if(b < 100000 && b >= 10000){ int last2 = lastDigit(b/10); int last3 = lastDigit(b/100); int last4 = lastDigit(b/1000); biggest = largestAbsVal5(last3, first, last, last2, last4); smallest = smallestAbsVal5(last3, first, last, last2, last4); return biggest - smallest + 1; } if(b < 1000000 && b >= 100000){ int last2 = lastDigit(b/10); int last3 = lastDigit(b/100); int last4 = lastDigit(b/1000); int last5 = lastDigit(b/10000); biggest = largestAbsVal6(last3, first, last, last2, last4, last5); smallest = smallestAbsVal6(last3, first, last, last2, last4, last5); return biggest - smallest + 1; } if(b < 10000000 && b >= 1000000){ int last2 = lastDigit(b/10); int last3 = lastDigit(b/100); int last4 = lastDigit(b/1000); int last5 = lastDigit(b/10000); int last6 = lastDigit(b/100000); biggest = largestAbsVal7(last3, first, last, last2, last4, last5, last6); smallest = smallestAbsVal7(last3, first, last, last2, last4, last5, last6); return biggest - smallest + 1; } if(b < 100000000 && b >= 10000000){ int last2 = lastDigit(b/10); int last3 = lastDigit(b/100); int last4 = lastDigit(b/1000); int last5 = lastDigit(b/10000); int last6 = lastDigit(b/100000); int last7 = lastDigit(b/1000000); biggest = largestAbsVal8(last3, first, last, last2, last4, last5, last6, last7); smallest = smallestAbsVal8(last3, first, last, last2, last4, last5, last6, last7); return biggest - smallest + 1; } if(b < 1000000000 && b >= 100000000){ int last2 = lastDigit(b/10); int last3 = lastDigit(b/100); int last4 = lastDigit(b/1000); int last5 = lastDigit(b/10000); int last6 = lastDigit(b/100000); int last7 = lastDigit(b/1000000); int last8 = lastDigit(b/10000000); biggest = largestAbsVal9(last3, first, last, last2, last4, last5, last6, last7, last8); smallest = smallestAbsVal9(last3, first, last, last2, last4, last5, last6, last7, last8); return biggest - smallest + 1; } if(b >= 1000000000){ int last2 = lastDigit(b/10); int last3 = lastDigit(b/100); int last4 = lastDigit(b/1000); int last5 = lastDigit(b/10000); int last6 = lastDigit(b/100000); int last7 = lastDigit(b/1000000); int last8 = lastDigit(b/10000000); int last9 = lastDigit(b/100000000); biggest = largestAbsVal10(last3, first, last, last2, last4, last5, last6, last7, last8, last9); smallest = smallestAbsVal10(last3, first, last, last2, last4, last5, last6, last7, last8, last9); return biggest - smallest + 1; } return 0; } public static int largestAbsVal(int a, int b, int c){ int max = Math.max(Math.abs(a), Math.abs(b)); return Math.max(max, Math.abs(c)); } public static int smallestAbsVal(int a, int b, int c){ int min = Math.min(Math.abs(a), Math.abs(b)); return Math.min(min, Math.abs(c)); } public static int smallestAbsVal4(int a, int b, int c, int d){ int min = Math.min(Math.abs(a), Math.abs(b)); int min2 = Math.min(Math.abs(c), Math.abs(d)); return Math.min(min, min2); } public static int largestAbsVal4(int a, int b, int c, int d){ int min = Math.max(Math.abs(a), Math.abs(b)); int min2 = Math.max(Math.abs(c), Math.abs(d)); return Math.max(min, min2); } public static int smallestAbsVal5(int a, int b, int c, int d, int e){ int min = Math.min(Math.abs(a), Math.abs(b)); int min2 = Math.min(Math.abs(c), Math.abs(d)); return smallestAbsVal(min, min2, e); } public static int largestAbsVal5(int a, int b, int c, int d, int e){ int min = Math.max(Math.abs(a), Math.abs(b)); int min2 = Math.max(Math.abs(c), Math.abs(d)); return largestAbsVal(min, min2, e); } public static int smallestAbsVal6(int a, int b, int c, int d, int e, int f){ int min = Math.min(Math.abs(a), Math.abs(b)); int min2 = Math.min(Math.abs(c), Math.abs(d)); int min3 = Math.min(Math.abs(e), Math.abs(f)); return smallestAbsVal(min, min2, min3); } public static int largestAbsVal6(int a, int b, int c, int d, int e, int f){ int min = Math.max(Math.abs(a), Math.abs(b)); int min2 = Math.max(Math.abs(c), Math.abs(d)); int max3 = Math.max(Math.abs(e), Math.abs(f)); return largestAbsVal(min, min2, max3); } public static int smallestAbsVal7(int a, int b, int c, int d, int e, int f, int ab){ int min = Math.min(Math.abs(a), Math.abs(b)); int min2 = Math.min(Math.abs(c), Math.abs(d)); int min3 = Math.min(Math.abs(e), Math.abs(f)); return smallestAbsVal4(min, min2, min3, ab); } public static int largestAbsVal7(int a, int b, int c, int d, int e, int f, int ab){ int min = Math.max(Math.abs(a), Math.abs(b)); int min2 = Math.max(Math.abs(c), Math.abs(d)); int max3 = Math.max(Math.abs(e), Math.abs(f)); return largestAbsVal4(min, min2, max3, ab); } public static int smallestAbsVal8(int a, int b, int c, int d, int e, int f, int ab, int g){ int min = Math.min(Math.abs(a), Math.abs(b)); int min2 = Math.min(Math.abs(c), Math.abs(d)); int min3 = Math.min(Math.abs(e), Math.abs(f)); return smallestAbsVal5(min, min2, min3, ab, g); } public static int largestAbsVal8(int a, int b, int c, int d, int e, int f, int ab, int g){ int min = Math.max(Math.abs(a), Math.abs(b)); int min2 = Math.max(Math.abs(c), Math.abs(d)); int max3 = Math.max(Math.abs(e), Math.abs(f)); return largestAbsVal5(min, min2, max3, ab, g); } public static int smallestAbsVal9(int a, int b, int c, int d, int e, int f, int ab, int g, int h){ int min = Math.min(Math.abs(a), Math.abs(b)); int min2 = Math.min(Math.abs(c), Math.abs(d)); int min3 = Math.min(Math.abs(e), Math.abs(f)); return smallestAbsVal6(min, min2, min3, ab, g, h); } public static int largestAbsVal9(int a, int b, int c, int d, int e, int f, int ab, int g, int h){ int min = Math.max(Math.abs(a), Math.abs(b)); int min2 = Math.max(Math.abs(c), Math.abs(d)); int max3 = Math.max(Math.abs(e), Math.abs(f)); return largestAbsVal6(min, min2, max3, ab, g, h); } public static int smallestAbsVal10(int a, int b, int c, int d, int e, int f, int ab, int g, int h, int i){

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 n) { if(n < 0){ return digitSum(-1 * n); }else if(n / 10 == 0){ return n; }else{ return n % 10 + digitSum(n / 10); } }

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.

public static int firstDigit(int number){ int length = 0; if(number < 0){ number = number / -1; } if(number < 10){ length = 1; } if(number < 100 && number >= 10){ length = 2; } if(number < 1000 && number >= 100){ length = 3; } if(number < 10000 && number >= 1000){ length = 4; } if(number < 100000 && number >= 10000){ length = 5; } if(number < 1000000 && number >= 100000){ length = 6; } length = length - 1; return number / ((int)Math.pow(10, length)) % 10; }

Write a method named gcd that accepts two integers as parameters and returns the greatest common divisor of the two numbers. The greatest common divisor (GCD) of two integers a and b is the largest integer that is a factor of both a and b. The GCD of any number and 1 is 1, and the GCD of any number and 0 is that number. One efficient way to compute the GCD of two numbers is to use Euclid's algorithm, which states the following: GCD(A, B) = GCD(B, A % B)GCD(A, 0) = Absolute value of A In other words, if you repeatedly mod A by B and then swap the two values, eventually B will store 0 and A will store the greatest common divisor. For example: gcd(24, 84) returns 12, gcd(105, 45) returns 15, and gcd(0, 8) returns 8.

public static int gcd(int a, int b){ if(b == 0){ return Math.abs(a); } if(a == 0){ return Math.abs(b); } int a1 = a % b; int a2 = b % a; if(b < 0 || a < 0){ b = Math.abs(b); } if(b < 0 || a < 0){ a = Math.abs(a); } if(b > a){ return gcd(b % a, a); } if(b < a){ return gcd(b, a % b); } return a; }

Write a static method called indexOf that takes two Strings and returns the index of the first occurrence of the second String in the first String. For example, the call indexOf("abcdefg", "cde") would return 2 because the String "cde" first occurs in "abcdefg" starting at index 2. If the second String does not appear in the first String, then -1 should be returned.

public static int indexOf(String s1, String s2) { for (int i = 0; i <= s1.length() - s2.length(); i++) { boolean matches = true; for (int j = 0; j < s2.length(); j++) { if (s1.charAt(i + j) != s2.charAt(j)) { matches = false; } } if (matches) { return i; } } return -1; }

Write a method named lastIndexOf that accepts an array of integers and an integer value as its parameters and returns the last index at which the value occurs in the array. The method should return -1 if the value is not found. For example, in the list containing {74, 85, 102, 99, 101, 85, 56}, the last index of the value 85 is 5.

public static int lastIndexOf(int[] integers, int i2){ for(int i = 0; i < integers.length; i++){ if(integers[integers.length - 1 - i] == i2){ return integers.length - 1 - i; } } return -1; }

Write a static method called printSequenceTo that takes a target value as a parameter and that prints terms from a particular numerical sequence until they add up to a value greater than or equal to the target and that returns the number of terms that were included. For example, if the following calls are made: int n1 = printSequenceTo(3.0); int n2 = printSequenceTo(5.5); The following output should be produced: 1/2 + 2/3 + 3/4 + 4/5 + 5/6 = 3.5500000000000003 1/2 + 2/3 + 3/4 + 4/5 + 5/6 + 6/7 + 7/8 + 8/9 = 6.171031746031746 The variable n1 is set to 5 because it took 5 terms from the sequence to get a sum that is at least 3.0. The variable n2 would be set to 8 because it took 8 terms to get a sum that is at least 5.5. You are to exactly reproduce the format of this output. You may assume that the target is greater than 0. Notice that the sum is not rounded.

public static int printSequenceTo(double n){ double b = 0; double count = 1; int count1 = 1; while(b < n){ b += (count) / (count1 + 1); if(b >= n){ System.out.print(count1 + "/" + (count1 + 1) + " = " + b); }else{ System.out.print(count1 + "/" + (count1 + 1) + " + "); } count++; count1++; } return count1 - 1; }

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: 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.

public static int quadrant(double a, double b){ if(a == 0 || b == 0){ return 0; } if(a > 0 && b < 0){ return 4; } int a1 = 1; if(a < 0){ a1++; } if(b < 0){ a1++; } return a1; }

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 b){ int b0 = 0; for(int i = 0; i < b.length(); i++){ char c = b.charAt(i); int b2 = 0; c = Character.toLowerCase(c); for(char bc = c; bc <= 'z'; bc++){ b2 += 1; } if(b2 < 14){ b0++; } } return b0; }

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) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; }

Write a method named swapDigitPairs that accepts a positive 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 ab){ int b1 = 0; int originalab = ab; boolean b = true; int i = 0; if(ab < 10){ return ab; } boolean odd = odd(ab); if(odd){ while(b){ int reallylastdigit = lastDigit(ab); int last2 = lastDigit(ab/10); if(ab < 10){ b = false; }else{ b1 += (last2 * (int)Math.pow(10, i)); b1 += (reallylastdigit * (int)Math.pow(10, i+1)); ab = ab/100; i+= 2; } if(ab == 0){ b = false; } } int firstd = firstDigit(originalab); b1 += firstd * (int)Math.pow(10, i); }else{ while(b){ int reallylastdigit = lastDigit(ab); int last2 = lastDigit(ab/10); b1 += (last2 * (int)Math.pow(10, i)); b1 += (reallylastdigit * (int)Math.pow(10, i+1)); ab = ab/100; i+= 2; if(ab == 0){ b = false; } } } return b1; } public static int lastDigit(int number){ if(number < 0){ number = number / -1; } return number % 10; } public static boolean odd(int number){ if(number < 0){ return odd(number / -1); } if(number < 10){ return true; } int count = 0; boolean b = true; while(b){ count++; number = number / 10; if(number == 0){ b = false; } } return count % 2 == 1; } public static int firstDigit(int n) { n = Math.abs(n); while(n > 9) { n /= 10; } return n; }

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 a){ int ab = 0; Scanner s = new Scanner(a); while(s.hasNext()){ String b = s.next(); ab++; } return ab; }

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 b){ boolean a = true; int b1 = 0; do{ if(b % 10 == 0){ b1++; } b = b / 10; if(b == 0 || b == 1){ a = false; } }while(a); return b1; }

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.

public static void diceSum(){ Scanner b = new Scanner(System.in); System.out.print("Desired dice sum: "); int a = b.nextInt(); boolean b2 = true; Random r = new Random(); while(b2){ int sum = 0; int ab = r.nextInt(6) + 1; int ab2 = r.nextInt(6) + 1; sum = ab + ab2; System.out.println(ab + " and " + ab2 + " = " + sum); if(sum == a){ b2 = false; } } }

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.

public static void evenSum(){ Scanner b = new Scanner(System.in); System.out.print("how many integers? "); int b1 = b.nextInt(); int b3 = 0; int b4 = -100000; for(int i = 0; i < b1; i++){ System.out.print("next integer? "); int i2 = b.nextInt(); if(i2 % 2 == 0 && i2 > b4){ b4 = i2; } if(i2 % 2 == 0){ b3 += i2; } } System.out.println("even sum = " + b3); System.out.println("even max = " + b4); }

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 findAllPerfectUpto 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 findAllPerfectUpto(6): Perfect numbers up to 6: 6 Here is the console output from a call to findAllPerfectUpto(500): Perfect numbers up to 500: 6 28 496

public static void findAllPerfectUpto(int n) { System.out.print("Perfect numbers up to " + n + ":"); for (int current = 1; current <= n; current++) { int sum = 0; for (int factor = 1; factor < current; factor++) { if (current % factor==0) { sum = sum+factor; } } if (sum == current) { System.out.print(" " + current); } } System.out.println(); }

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.

public static void inputBirthday(Scanner b){ System.out.print("On what day of the month were you born? "); int b1 = b.nextInt(); System.out.print("What is the name of the month in which you were born? "); String b2 = b.next(); System.out.print("During what year were you born? "); int b3 = b.nextInt(); System.out.println("You were born on " + b2 + " " + b1 + ", " + b3 + ". You're mighty old!"); }

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 (user input in blue):

public static void longestName(Scanner b, int b1){ int b2 = 0; String b11 = ""; boolean b22 = false; for(int i = 0; i < b1; i++){ System.out.print("name #" + (i + 1) + "? "); String b0 = b.next(); int b3 = b0.length(); if(b3 == b2){ b22 = true; } if(b3 > b2){ b2 = b3; b11 = b0; b22 = false; } } System.out.println(Character.toUpperCase(b11.charAt(0)) + b11.substring(1).toLowerCase() + "'s name is longest"); if(b22){ System.out.println("(There was a tie!)"); } }

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.

public static void makeGuesses(){ Random r = new Random(); int b = r.nextInt(50) + 1; if(b >= 48){ System.out.println("guess = " + b); System.out.println("total guesses = 1"); }else{ int a = 1; boolean bool = true; while(bool){ System.out.println("guess = " + b); if(b >= 48){ bool = false; } a++; b = r.nextInt(50) + 1; } System.out.println("total guesses = " + a); } }

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 ab){ System.out.print("Perfect numbers up to " + ab + ":"); for(int i = 5; i <= ab; i++){ int sum = 0; for(int j = 1; j < i - 1; j++){ if(i % j != 0){ }else{ sum += j; } } if(sum == i){ System.out.print(" " + i); } } }

Write a method called printAcronym that accepts a String as its parameter and prints the first letter of each word of the string as an acronym. For example, the call of printAcronym("Breath of the Wild") should print "BotW". You may assume that the string contains at least one word and does not have any surrounding whitespace at its start or end.

public static void printAcronym(String b){ if(!(b.contains(" "))){ System.out.println((b.charAt(0) + "").toUpperCase()); } String a = b.charAt(0) + ""; a = a.toUpperCase(); for(int i = 1; i < b.length(); i++){ if(b.charAt(i) == ' '){ String b1 = b.charAt(i + 1) + ""; a += b1; } } System.out.println(a); }

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);

public static void printAverage(Scanner ab){ double b = 0; int b0 = 0; boolean a = true; while(a){ System.out.print("Type a number: "); int a0 = ab.nextInt(); if(a0 < 0){ a = false; }else{ b += a0; } b0++; } if(b0 > 1){ System.out.println("Average was " + (b / (0.0 + b0 - 1))); } }

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 static void printFactors(int n){ System.out.print("1"); int b = 0; for (int i = 2; i <= n; i++) { if (n % i == 0) { // a factor System.out.print(" and " + 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 b = new Scanner(System.in); System.out.print("Enter a student record: "); String b2 = b.nextLine(); Scanner b1 = new Scanner(b2); String b0 = b1.next(); double sum = 0; int count = 0; int ignore = b1.nextInt(); while(b1.hasNextInt()){ double b3 = b1.nextInt() + 0.0; sum += b3; count++; } System.out.println(b0 + "'s grade is " + (sum / count)); }

Write a method named printGrid that accepts two integer parameters rows and cols. The output is a comma-separated grid of numbers where the first parameter (rows) represents the number of rows of the grid and the second parameter (cols) represents the number of columns. The numbers count up from 1 to (rows x cols). The output are displayed in column-major order, meaning that the numbers shown increase sequentially down each column and wrap to the top of the next column to the right once the bottom of the current column is reached. Assume that rows and cols are greater than 0.

public static void printGrid(int row, int col){ for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ System.out.print(i+1 + (j * row)); if(j < col - 1){ System.out.print(", "); } } System.out.println(); } }

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.

public static void printIndexed(String b){ int b1 = 0; for(int i = b.length() - 1; i >= 0; i--){ System.out.print(b.charAt(b1)); System.out.print(i); b1++; } }

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) { if(text.length() <= 1){ System.out.println(text); }else{ for (int i = 0; i < text.length(); i++) { if(i < text.length() - 1){ System.out.print(text.charAt(i) + "-"); }else{ System.out.print(text.charAt(i)); } } System.out.println(); // to end the line of output } }

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. For an added challenge, make the code case-insensitive, so that words like "Abba" and "Madam" will be considered palindromes.

public static void printPalindrome(Scanner b){ System.out.print("Type one or more words: "); String b1 = b.nextLine(); if(b1.contains(" ")){ method(b1); return; } Scanner a = new Scanner(b1); while(a.hasNext()){ String b2 = a.next(); String a2 = b2.toLowerCase(); int b3 = b2.length(); //String a1 = b2.substring(0, 1 + b3 / 2); //String a11 = b2.substring(1 + b3 / 2); boolean a4 = true; for(int i = 0; i < b3; i++){ char a0 = a2.charAt(i); char a3 = a2.charAt(b3 - 1 - i); if(a0 != a3){ a4 = false; } } if(a4){ System.out.println(b2 + " is a palindrome!"); }else{ System.out.println(b2 + " is not a palindrome."); } } } public static void method(String b1){ String c = " "; boolean ab = true; Scanner a = new Scanner(b1); String b13 = a.next(); String b4 = a.next(); String a2 = b13.toLowerCase(); int b3 = b13.length(); //String a1 = b2.substring(0, 1 + b3 / 2); //String a11 = b2.substring(1 + b3 / 2); for(int i = 0; i < b3; i++){ char a0 = a2.charAt(i); char a3 = b4.toLowerCase().charAt(b3 - 1 - i); if(a0 != a3){ ab = false; } } if(ab){ System.out.println(b13 + c + b4 + " is a palindrome!"); }else{ System.out.println(b13 + c + b4 + " is not a palindrome."); } }

Write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from base0 (1) up to that maximum power, inclusive. For example, consider the following calls: printPowersOfN(4, 3); printPowersOfN(5, 6); printPowersOfN(-2, 8);

public static void printPowersOfN(int e, int x){ System.out.print("1 "); int prev = 1; for(int i = 1; i <= x; i++){ System.out.print(((e)* prev) + " "); prev = e * prev; } System.out.println(); }

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:

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

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 the following output: !ereht olleh If the empty string is passed, no output is produced. Your method should produce a complete line of output.

public static void printReverse(String b){ for(int i = 0; i < b.length(); i++){ System.out.print(b.charAt(b.length() - 1 - i) + ""); } }

Write a method called printSquare that takes in two integer parameters, a min and a max, and prints the numbers in the range from min to max inclusive in a square pattern. The square pattern is easier to understand by example than by explanation, so take a look at the sample method calls and their resulting console output in the table below. Each line of the square consists of a circular sequence of increasing integers between min and max. Each line prints a different permutation of this sequence. The first line begins with min, the second line begins with min + 1, and so on. When the sequence in any line reaches max, it wraps around back to min. You may assume the caller of the method will pass a min and a max parameter such that min is less than or equal to max.

public static void printSquare(int a, int b){ int count = 0; if(b - a == 0){ System.out.print(a); }else{ for(int i = 0; i < b; i++){ for(int j = a; j <= b; j++){ if((i + j) > b){ System.out.print(i + j - method(i, j, a, b) + count); count++; if(j == b){ count = 0; } }else{ System.out.print(i + j); } } System.out.println(); if(i > (b-a-1)){ i += 100; } if(a == 0 && i == b - 1){ for(int j = a + 1; j <= b; j++){ if((i + j) > b){ System.out.print(i + j - method(i, j, a, b) + count); count++; if(j == b){ count = 0; } }else{ System.out.print(i + j); } } System.out.print(b - 1); } } } } public static int method(int i, int j, int a, int b){ int calculation = a - j; return Math.abs(calculation - i); }

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.

public static void printTriangleType(int b1, int b2, int b3){ if(b1 == b2 && b2 == b3){ System.out.println("equilateral"); }else if(b1 == b2 || b2 == b3 || b1 == b3){ System.out.println("isosceles"); }else{ System.out.println("scalene"); } }

Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary.

public static void processName(Scanner b){ System.out.print("Please enter your full name: "); String b1 = b.nextLine(); int b2 = b1.indexOf(" "); String b3 = b1.substring(b2 + 1); String b4 = b1.substring(0, b2); System.out.println("Your name in reverse order is " + b3 + ", " + b4); }

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 x of the form a x2 + b x + c = 0. Your method should accept the coefficients a, b, and c as parameters and should print the roots of the equation. You may assume that the equation has two real roots, though mathematically this is not always the case. Also, there should be two roots, one the result of the addition, the other, the result of the subtraction. Print the root resulting from the addition first.

public static void quadratic(int a, int b, int c){ double d = Math.pow(b, 2); double e = 4 * a * c; double f = Math.sqrt(d - e); double g1 = (-b + f)/(2*a); double g2 = (-b - f)/(2 *a); System.out.println("First root = " + g1); System.out.println("Second root = " + g2); }

Exercise 3.8 asked you to 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 x of the form a x2 + b x + c = 0. But for some values of a, b, and c, the formula does not find any valid roots. Under what conditions would this formula fail? Modify the quadratic method so that it will reject invalid values of a, b, or c by throwing an IllegalArgumentException. (You may want to go back and complete the exercise in the previous chapter first.)

public static void quadratic(int a, int b, int c){ double d = Math.pow(b, 2); double e = 4 * a * c; if(d - e < 0){ throw new IllegalArgumentException(); } double f = Math.sqrt(d - e); if(a == 0){ throw new IllegalArgumentException(); } double g1 = (-b + f)/(2*a); double g2 = (-b - f)/(2 *a); System.out.println("First root = " + g1); System.out.println("Second root = " + g2); }

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 x = new Random(); int ab = x.nextInt(5) + 5; int count = 0; while(count < ab){ int ib = x.nextInt(80); for(int i = 0; i < ib; i++){ char c = (char)(x.nextInt(25) + 97); System.out.print(c); } System.out.println(); count++; } }

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:

public static void randomWalk(){ int ab = 0; Random r = new Random(); boolean bool = true; int max = -3; while(bool){ System.out.println("position = " + ab); int b1 = r.nextInt(2); if(ab == -3 || ab == 3){ bool = false; } if(ab > max){ max = ab; } if(b1 == 1){ ab++; }else{ ab--; } } System.out.println("max position = " + max); }

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.

public static void randomX(){ Random x = new Random(); int ia = x.nextInt(15) + 5; if(ia >= 16){ for(int i = 0; i < ia; i++){ System.out.print("x"); } System.out.println(); }else{ boolean bool = true; while(bool){ int ib = x.nextInt(14) + 5; if(ia >= 16){ bool = false; } for(int i = 0; i < ia; i++){ System.out.print("x"); } System.out.println(); ia = ib; } } }


Related study sets

Chapter 6 - Electromagnetic Induction

View Set

Analysis (Basic Tax Rules) - Fundamental : Review Questions

View Set

Assessment r/t Acid Base Imbalance

View Set

SLCC Human Bio Mitosis, Meiosis, and Cancer

View Set

Chapter 11: stereotypes, prejudice, and discrimination

View Set