CS final

Ace your homework & exams now with Quizwiz!

Write a for loop that produces the following output: 1 4 9 16 25 36 49 64 81 100

int a,i; for(i=1;i<=10;i++) System.out.print(i*i + " ");

The Fibonacci numbers are a sequence of integers in which the first two elements are 1, and each following element is the sum of the two preceding elements. The mathematical definition of each kth Fibonacci number is the following: F(k): k > 2 : F(k-1) + F(k-2) k <= 2 : 1 The first 12 Fibonacci numbers are: 1 1 2 3 5 8 13 21 34 55 89 144 Write a piece of code that uses a for loop to compute and print the first 12 Fibonacci numbers. (You may include other code, such as declaring variables before the loop, if you like.)

int a=1; int b=1; int c=2; System.out.print(a + " " +b + " "); for (int i=3; i<=12; i++){ c=a+b; b=a; a=c; System.out.print(c + " "); }

Write a complete Java program in a class named Egg that displays the following output: _______ / \ / \ -"-'-"-'-"- \ / \_______/

public class Egg { public static void main(String[]args){ System.out.println(" _______ "); System.out.println(" / \\ "); System.out.println("/ \\ "); System.out.println("-\"-'-\"-'-\"- "); System.out.println("\\ / "); System.out.println(" \\_______/ "); } }

Write a complete Java program in a class named Spikey that prints the following output: \/ \\// \\\/// ///\\\ //\\ /\

public class Spikey { public static void main(String[]args) { System.out.println(" \\/"); System.out.println(" \\\\//"); System.out.println("\\\\\\///"); System.out.println("///\\\\\\"); System.out.println(" //\\\\"); System.out.println(" /\\"); } }

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 For an added challenge, make your method throw an IllegalArgumentException if the user passes a grade lower than 0 or higher than 100.

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

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

Write a method called kthLargest that accepts an integer k and an array a as its parameters and returns the element such that k elements have greater or equal value. If k = 0, return the largest element; if k = 1, return the second largest element, and so on. For example, if the array passed contains the values {74, 85, 102, 99, 101, 56, 84} and the integer k passed is 2, your method should return 99 because there are two values at least as large as 99 (101 and 102). Assume that 0 <= k < a.length. (Hint: Consider sorting the array, or a copy of the array first.)

public int kthLargest(int k, int[] d) { Arrays.sort(d); return d[d.length-k-1]; }

Write a method called append that accepts two integer arrays as parameters and returns a new array that contains the result of appending the second array's values at the end of the first array. For example, if arrays list1 and list2 store {2, 4, 6} and {1, 2, 3, 4, 5} respectively, the call of append(list1, list2) should return a new array containing {2, 4, 6, 1, 2, 3, 4, 5}. If the call instead had been append(list2, list1), the method would return an array containing {1, 2, 3, 4, 5, 2, 4, 6}.

public int[] append(int[] list1, int[] list2) { int n1 = list1.length; int n2 = list2.length; int[] data = new int[n1+n2]; for (int i=0; i<n1; i++) { data[i] = list1[i]; } for (int i=0; i<n2; i++) { data[n1+i] = list2[i]; } return data; }

Write a method called collapse that accepts an array of integers as a parameter and returns a new array containing the result of replacing each pair of integers with the sum of that pair. For example, if an array called list stores the values {7, 2, 8, 9, 4, 13, 7, 1, 9, 10}, then the call of collapse(list) should return a new array containing {9, 17, 17, 8, 19}. The first pair from the original list is collapsed into 9 (7 + 2), the second pair is collapsed into 17 (8 + 9), and so on. If the list stores an odd number of elements, the final element is not collapsed. For example, if the list had been {1, 2, 3, 4, 5}, then the call would return {3, 7, 5}. Your method should not change the array that is passed as a parameter.

public int[] collapse(int[] d) { int n = d.length; int[] res = new int[(n+1)/2]; int i=0; int j=0; while (i < n-1) { res[j] = d[i] + d[i+1]; j++; i += 2; } if (i == n-1) res[j] = d[i]; return res; }

c method named vowelCount that accepts a String as a parameter and produces and returns an array of integers representing the counts of each vowel in the String. The array returned by your method should hold 5 elements: the first is the count of As, the second is the count of Es, the third Is, the fourth Os, and the fifth Us. Assume that the string contains no uppercase letters. For example, the call vowelCount("i think, therefore i am") should return the array {1, 3, 3, 1, 0}.

public int[] vowelCount(String x) { int[] res = new int[5]; for (int i=0; i<x.length(); i++) { char ch = x.charAt(i); if (ch == 'a') { res[0]++; } else if (ch == 'e') { res[1]++; } else if (ch == 'i') { res[2]++; } else if (ch == 'o') { res[3]++; } else if (ch == 'u') { res[4]++; } } return res; }

Write a static method named contains that accepts two arrays of integers a1 and a2 as parameters and that returns a boolean value indicating whether or not a2's sequence of elements appears in a1 (true for yes, false for no). The sequence of elements in a2 may appear anywhere in a1 but must appear consecutively and in the same order. For example, if variables called list1 and list2 store the following values: int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8}; int[] list2 = {1, 2, 1}; Then the call of contains(list1, list2) should return true because list2's sequence of values {1, 2, 1} is contained in list1 starting at index 5. If list2 had stored the values {2, 1, 2}, the call of contains(list1, list2) would return false because list1 does not contain that sequence of values. Any two lists with identical elements are considered to contain each other, so a call such as contains(list1, list1) should return true. You may assume that both arrays passed to your method will have lengths of at least 1. You may not use any Strings to help you solve this problem, nor methods that produce Strings such as Arrays.toString.

public static boolean contains (int [] a1, int [] a2){ for(int j=0;j<=a1.length-a2.length;j++){ int count=0; for(int i=0;i<a2.length;i++){ if(a2[i]==a1[i+j]){ count++; } } if (count==a2.length){ return true; } } return false; }

Write a static method named isSorted that accepts an array of doubles as a parameter and returns true if the list is in sorted (nondecreasing) order and false otherwise. For example, if arrays named list1 and list2 store {16.1, 12.3, 22.2, 14.4} and {1.5, 4.3, 7.0, 19.5, 25.1, 46.2} respectively, the calls isSorted(list1) and isSorted(list2) should return false and true respectively. Assume the array has at least one element. A one-element array is considered to be sorted.

public static boolean isSorted(double[] data) { for (int i=1; i<data.length; i++) { if (data[i] < data[i-1]){ return false; } } return true; }

d named isUnique that takes an array of integers as a parameter and that returns a boolean value indicating whether or not the values in the array are unique (true for yes, false for no). The values in the list are considered unique if there is no pair of values that are equal. For example, if a variable called list stores the following values: int[] list = {3, 8, 12, 2, 9, 17, 43, -8, 46, 203, 14, 97, 10, 4}; Then the call of isUnique(list) should return true because there are no duplicated values in this list. If instead the list stored these values: int[] list = {4, 7, 2, 3, 9, 12, -47, -19, 308, 3, 74}; Then the call should return false because the value 3 appears twice in this list. Notice that given this definition, a list of 0 or 1 elements would be considered unique.

public static boolean isUnique(int []data){ Arrays.sort(data); for(int i=1;i<data.length;i++){ if(data[i]==data[i-1]){ return false; } } return true; }

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. The formula for the surface area of a cylinder with radius r and height h is the following: surface area = 2πr2 + 2πrh

public static double cylinderSurfaceArea(double radius, double height){ return Math.PI*2*(radius*radius)+2*Math.PI*radius*height; }

Write a method called distance that accepts four integer coordinates x1, y1, x2, and y2 as parameters and computes the distance between points (x1, y1) and (x2, y2) on the Cartesian plane. The equation for the distance is: distance equation 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 x1, int y1, int x2, int y2){ return (Math.sqrt(Math.pow( x2-x1,2)+ Math.pow( y2-y1,2))); }

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 called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements {6, 2, 9, 11, 3}, then your method should return 40.0. If the array contains no even elements or no elements at all, return 0.0.

public static double percentEven(int []data){ if(data.length==0){ return 0.0; } int count=0; for(int i=0;i<data.length;i++){ if(data[i]%2==0){ count++; } } return 100.0*count/data.length; }

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 base, double exponet){ return base* Math.pow(10, exponet); }

Write a method called stdev that returns the standard deviation of an array of integers. Standard deviation is computed by taking the square root of the sum of the squares of the differences between each element and the mean, divided by one less than the number of elements. (It's just that simple!) More concisely and mathematically, the standard deviation of an array a is written as follows: standard deviation For example, if the array passed contains the values {1, -2, 4, -4, 9, -6, 16, -8, 25, -10}, your method should return approximately 11.237. You may assume that the array passed is non-null and contains at least two values, because the standard deviation is undefined otherwise. (Note: you might fail the last two tests because of rounding, but as long as it's close, then your algorithm is probably correct.)

public static double stdev(int[] numbers){ double sum = 0; double sd = 0; for(int i = 0; i < numbers.length; i++){ sum = sum + numbers[i]; } double average = sum / numbers.length; for(int i = 0; i < numbers.length; i++){ sd +=+ Math.pow(numbers[i] - average, 2); } double SDD = Math.sqrt(sd/ (numbers.length - 1)); return SDD; }

Write a method called countInRange that accepts an array of integers, a minimum value, and a maximum value as parameters and returns the count of how many elements from the array fall between the minimum and maximum (inclusive). For example, in the array {14, 1, 22, 17, 36, 7, -43, 5}, there are four elements whose values fall between 4 and 17.

public static int countInRange (int []data, int min, int max){ int count=0; for(int i=0;i<data.length;i++){ if(data[i]<=max && data[i]>=min){ 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). Month 1 Jan 2 Feb 3 Mar 4 Apr 5 May 6 Jun 7 Jul 8 Aug 9 Sep 10 Oct 11 Nov 12 Dec Days 31 28 31 30 31 30 31 31 30 31 30 31

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

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

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

Write a method 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 x, int y, int z){ int ans= Math.max(Math.abs(x), Math.abs(y)); return Math.max(Math.abs(z), ans); }

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. Call Value Returned lastDigit(3572) 2 lastDigit(-947) 7 lastDigit(6) 6 lastDigit(35) 5 lastDigit(123456) 6 (Hint: This is a short method. You may not use a String to solve this problem.)

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

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[] data, int x) { for (int i=data.length-1; i>=0; i--) { if (data[i] == x) { return i; } } return -1; }

Write a method named longestSortedSequence that accepts an array of integers as a parameter and that returns the length of the longest sorted (nondecreasing) sequence of integers in the array. For example, if a variable named array stores the following values: int[] array = {3, 8, 10, 1, 9, 14, -3, 0, 14, 207, 56, 98, 12}; then the call of longestSortedSequence(array) should return 4 because the longest sorted sequence in the array has four values in it (the sequence -3, 0, 14, 207). Notice that sorted means nondecreasing, which means that the sequence could contain duplicates. For example, if the array stores the following values: int[] array2 = {17, 42, 3, 5, 5, 5, 8, 2, 4, 6, 1, 19} Then the method would return 5 for the length of the longest sequence (the sequence 3, 5, 5, 5, 8). Your method should return 0 if passed an empty array.

public static int longestSortedSequence(int []data){ if(data.length==0){ return 0; }else{ int count=1; int longest=1; for(int i=0;i<data.length-1;i++){ if(data[i]<=data[i+1]){ count++; if(count>longest){ longest=count; } }else{ count=1; } } return longest; } }

Write a method called median that accepts an array of integers as its argument and returns the median of the numbers in the array. The median is the number that will appear in the middle if you arrange the elements in order. Assume that the array is of odd size (so that one sole element constitutes the median) and that the numbers in the array are between 0 and 99 inclusive. For example, the median of {5, 2, 4, 17, 55, 4, 3, 26, 18, 2, 17} is 5, and the median of {42, 37, 1, 97, 1, 2, 7, 42, 3, 25, 89, 15, 10, 29, 27} is 25. (Hint: You may wish to look at the Tally program from earlier in this chapter for ideas.)

public static int median(int[] d) { Arrays.sort(d); return d[d.length/2]; }

d named minGap that accepts an integer array as a parameter and returns the minimum 'gap' between adjacent values in the array. The gap between two adjacent values in a array is defined as the second value minus the first value. For example, suppose a variable called array is an array of integers that stores the following sequence of values. int[] array = {1, 3, 6, 7, 12}; The first gap is 2 (3 - 1), the second gap is 3 (6 - 3), the third gap is 1 (7 - 6) and the fourth gap is 5 (12 - 7). Thus, the call of minGap(array) should return 1 because that is the smallest gap in the array. Notice that the minimum gap could be a negative number. For example, if array stores the following sequence of values: {3, 5, 11, 4, 8} The gaps would be computed as 2 (5 - 3), 6 (11 - 5), -7 (4 - 11), and 4 (8 - 4). Of these values, -7 is the smallest, so it would be returned. This gap information can be helpful for determining other properties of the array. For example, if the minimum gap is greater than or equal to 0, then you know the array is in sorted (nondecreasing) order. If the gap is greater than 0, then you know the array is both sorted and unique (strictly increasing). If you are passed an array with fewer than 2 elements, you should return 0.

public static int minGap(int []data){ if(data.length<2){ return 0; } int min=data[1]-data[0]; for(int i=2;i<data.length;i++){ int gap=data[i]-data[i-1]; if(gap<min){ min=gap; } } return min; }

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value. For example, if the array passed contains the values {27, 15, 15, 11, 27}, your method should return 15. (Hint: You may wish to look at the Tally program from earlier in this chapter to get an idea of how to solve this problem.)

public static int mode (int []array){ int [] data=new int [101]; for(int i=0;i<array.length;i++){ data[array[i]]++; } int mode=101; int count=0; for(int i=0;i<data.length;i++){ if(data[i]>count){ count=data[i]; mode=i; } } return mode; }

Write a method named mostCommonNames that accepts as its parameter a Scanner for an input file whose data is a sequence of lines, where each line contains a set of first names separated by spaces. Your method should print the name that occurs the most frequently in each line of the file. The method should also return the total number of unique names that were seen in the file. You may assume that no name appears on more than one line of the file. Each line should be considered separately from the others. On a given line, some names are repeated; all occurrences of a given name will appear consecutively in the file. If two or more names occur the same number of times, print the one that appears earlier in the file. If every single name on a given line is different, every name will have 1 occurrence, so you should just print the first name in the file. For example, if the input file contains the following text: Benson Eric Eric Marty Kim Kim Kim Jenny Nancy Nancy Nancy Paul Paul Stuart Stuart Stuart Ethan Alyssa Alyssa Helene Jessica Jessica Jessica Jessica Jared Alisa Yuki Catriona Cody Coral Trent Kevin Ben Stefanie Kenneth On the first line, there is one occurrence of the name Benson, two occurrences of Eric, one occurrence of Marty, three occurrences of Kim, one of Jenny, three of Nancy, and two of Paul. Kim and Nancy appear the most times (3), and Kim appears first in the file. So for that line, your method should print that the most common is Kim. The complete output would be the following. The method would also return 23, since there are 23 unique names in the entire file. Most common: Kim Most common: Jessica Most common: Jared You may assume that there is at least one line of data in the file and that each line will contain at least one name.

public static int mostCommonNames(Scanner input){ int uniqueName=0; while(input.hasNextLine()){ String line=input.nextLine(); Scanner console=new Scanner (line); String last=console.next(); uniqueName++; String commonWord=last; int mostCommon=1; int count=1; while(console.hasNext()){ String current=console.next(); if(current.equals(last)){ count++; }else{ if(count>mostCommon){ mostCommon=count; commonWord=last; } count=1; uniqueName++; } last=current; } if(count>mostCommon){ commonWord=last; } System.out.println("Most common: "+commonWord); } return uniqueName; }

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 method priceIsRight that accepts an array of integers bids and an integer price as parameters. The method returns the element in the bids array that is closest in value to price without being larger than price. For example, if bids stores the elements {200, 300, 250, 999, 40}, then priceIsRight(bids, 280) should return 250, since 250 is the bid closest to 280 without going over 280. If all bids are larger than price, then your method should return -1. The following table shows some calls to your method and their expected results: Arrays Returned Value int[] a1 = {900, 885, 989, 1}; priceIsRight(a1, 800) returns 1 int[] a2 = {200}; priceIsRight(a2, 120) returns -1 int[] a3 = {500, 300, 241, 99, 501}; priceIsRight(a3, 50) returns -1 You may assume there is at least 1 element in the array, and you may assume that the price and the values in bids will all be greater than or equal to 1. Do not modify the contents of the array passed to your method as a parameter.

public static int priceIsRight(int []bids, int price){ int min=0; for (int i=0; i< bids.length; i++) { if (bids[i] <= price && bids[i] > min) min = bids[i]; } if (min == 0) return -1; return min; }

Write a static method named range that takes an array of integers as a parameter and returns the range of values contained in the array. The range of an array is defined to be one more than the difference between its largest and smallest element. For example, if the largest element in the array is 15 and the smallest is 4, the range is 12. If the largest and smallest values are the same, the range is 1. The following table shows some calls to your method and their results (the largest and smallest values are underlined): Call Value Returned int[] a1 = {8, 3, 5, 7, 2, 4}; range(a1) returns 7 int[] a2 = {15, 22, 8, 19, 31}; range(a2) returns 24 int[] a3 = {3, 10000000, 5, -29, 4}; range(a3) returns 10000030 int[] a4 = {100, 5}; range(a4) returns 96 int[] a5 = {32}; range(a5) returns 1 You may assume that the array contains at least one element (that its length is at least 1). You should not make any assumptions about the values of the particular elements in the array; they could be extremely large, very small, etc. You should not modify the contents of the array.

public static int range(int[] data) { int min = data[0], max = data[0]; for (int i=0;i<data.length;i++) { if (data[i] < min) { min = data[i]; } if (data[i]> max) { max = data[i]; } } return max-min+1; }

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

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

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 in = new Scanner(System.in); System.out.print("how many integers? "); int n = in.nextInt(); int s=0; int t = 0; int m = 0; for(int i=0;i<n;i++){ System.out.print("next integer? "); t=in.nextInt(); if(t%2==0){ s=s+t; if(t>m) m=t; } } System.out.println("even sum = "+s); System.out.println("even max = "+m); }

Write a method named inputStats that takes a Scanner representing a file as a parameter and that reports various statistics about the file's text. In particular, your method should report the number of lines in the file, the longest line, the number of tokens on each line, and the length of the longest token on each line. You may assume that the input file has at least one line of input and that each line has at least one token. For example, if a Scanner named input on file carroll.txt contains the following text: "Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch." then the call inputStats(input); should produce the following output: Line 1 has 5 tokens (longest = 11) Line 2 has 8 tokens (longest = 6) Line 3 has 6 tokens (longest = 6) Line 4 has 3 tokens (longest = 14) Longest line: the jaws that bite, the claws that catch,

public static void inputStats(Scanner input){ int lineNum=0; int longestLine=0; String longestString=""; while(input.hasNextLine()){ lineNum++; String line=input.nextLine(); if(line.length()>longestLine){ longestLine=line.length(); longestString=line; } int token=0; int longest=0; Scanner console=new Scanner (line); while(console.hasNext()){ token++; String word=console.next(); if(word.length()>longest){ longest=word.length(); } } System.out.printf("Line %d has %d tokens (longest = %d)\n", lineNum, token, longest); } System.out.println("Longest line: "+longestString); }

Write a static method named plusScores that accepts as a parameter a Scanner containing a series of lines that represent student records. Each student record takes up two lines of input. The first line has the student's name and the second line has a series of plus and minus characters. Below is a sample input: Kane, Erica --+-+ Chandler, Adam ++-+ Martin, Jake +++++++ Dillon, Amanda ++-++-+- The number of plus/minus characters will vary, but you may assume that at least one such character appears and that no other characters appear on the second line of each pair. For each student you should produce a line of output withthe student's name followed by a colon followed by the percent of plus characters. For example, if the input above is stored in a Scanner called input, the call of plusScores(input); should produce the following output: Kane, Erica: 40.0% plus Chandler, Adam: 75.0% plus Martin, Jake: 100.0% plus Dillon, Amanda: 62.5% plus

public static void plusScores(Scanner in) { while(in.hasNextLine()) { String name = in.nextLine(); String score = in.nextLine(); int n=0; int p=0; for (int i=0; i<score.length(); i++) { if(score.charAt(i) == '+') { p++; } n++; } System.out.printf("%s: %.1f%% plus\n", name, 100.0*p/n); } }

Write a method called printDesign that produces the following output. Use nested for loops to capture the structure of the figure. -----1----- ----333---- ---55555--- --7777777-- -999999999-

public static void printDesign() { for (int rows=1; rows<=5;rows++){ for (int dashes=1; dashes <= -1*rows+6; dashes++){ System.out.print("-"); } for (int numbers=1; numbers<=2*rows-1; numbers++){ System.out.print(2*rows-1); } for (int dashes=1; dashes <= -1*rows+6; dashes++){ System.out.print("-"); } System.out.println(); } }

Write a method named printDuplicates that accepts as its parameter a Scanner for an input file containing a series of lines. Your method should examine each line looking for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively. Non-repeated tokens are not printed. Repetition across multiple lines (such as if a line ends with a given token and the next line starts with the same token) is not considered in this problem. For example, if the input file contains the following text: hello how how are you you you you I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge bow wow wow yippee yippee yo yippee yippee yay yay yay one fish two fish red fish blue fish It's the Muppet Show, wakka wakka wakka Your method would produce the following output for the preceding input file: how*2 you*4 I*3 Jack's*2 smirking*5 wow*2 yippee*2 yippee*2 yay*3 wakka*3 Your code prints only the repeated tokens; the ones that only appear once in a row are not shown. Your code should place a single space between each reported duplicate token and should respect the line breaks in the original file. This is why a blank line appears in the expected output, corresponding to the fourth line of the file that did not contain any consecutively duplicated tokens. You may assume that each line of the file contains at least 1 token of input.

public static void printDuplicates (Scanner input){ while(input.hasNextLine()){ String line=input.nextLine(); Scanner console=new Scanner (line); String last=console.next(); int count=1; while(console.hasNext()){ String current=console.next(); if(last.equals(current)){ count++; }else{ if(count>1){ System.out.print(last+"*"+count+" "); } count=1; } last=current; } if(count>1){ System.out.print(last+"*"+count+" "); } System.out.println(); } }

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

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

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

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

Write a method called vertical that accepts a String as its parameter and prints each letter of the string on separate lines. For example, a call of vertical("hey now") should produce the following output: h e y n o w

public static void vertical(String phrase){ for (int i=0;i<phrase.length();i++){ System.out.println(phrase.substring(i,i+1)); } } or public static void vertical(String phrase){ for (int i=0;i<phrase.length();i++){ System.out.println(phrase.charAt(i)); } }

Write a method called wordLengths that accepts a Scanner representing an input file as its argument. Your method should read from the given file, count the number of letters in each token in the file, and output a result diagram of how many words contain each number of letters. Use tabs before the asterisks so that they'll line up. If there are no words of a given length, omit that line from the output. For example, if the file contains the following text: Before sorting: 13 23 480 -18 75 hello how are you feeling today After sorting: -18 13 23 75 480 are feeling hello how today you your method should produce the following output to the console: 2: 6 ****** 3: 10 ********** 5: 5 ***** 6: 1 * 7: 2 ** 8: 2 **

public static void wordLengths (Scanner console){ int [] array=new int[81]; while(console.hasNext()){ array[console.next().length()]++; } for(int i=1;i<array.length;i++){ if (array[i]!=0){ System.out.printf("%d: %d\t", i, array[i]); for(int j=0;j<array[i];j++){ System.out.print("*"); } System.out.println(); } } }

Write a method called wordWrap that accepts a Scanner representing an input file as its parameter and outputs each line of the file to the console, word-wrapping all lines that are longer than 60 characters. For example, if a line contains 112 characters, the method should replace it with two lines: one containing the first 60 characters and another containing the final 52 characters. A line containing 217 characters should be wrapped into four lines: three of length 60 and a final line of length 37.

public static void wordWrap(Scanner Input){ String line; while(Input.hasNextLine()){ line=Input.nextLine(); while (line.length() > 60) { System.out.println(line.substring(0, 60)); line = line.substring(60); } System.out.println(line); } }

Modify the preceding wordWrap method into a new wordWrap2 method that accepts a second parameter for a PrintStream to write the data, and outputs the newly wrapped text to that PrintStream rather than to the console. Also, modify it to use a local variable to store the maximum line length rather than hard-coding 60. (You can go back to the last problem to copy your solution code from there and paste it here as a starting point.)

public static void wordWrap2(Scanner Input, PrintStream out){ String line; while(Input.hasNextLine()){ line=Input.nextLine(); while (line.length() > 60) { out.println(line.substring(0, 60)); line = line.substring(60); } out.println(line); } }

Modify the preceding wordWrap method into a new wordWrap3 method that wraps only whole words, never chopping a word in half. Assume that a word is any whitespace-separated token and that all words are under 60 characters in length. Make sure that each time you wrap a line, the subsequent wrapped line(s) each begin with a word and not with any leading whitespace. Accept only a single parameter for the input Scanner, and send your method's output to the console, as in the original wordWrap problem; do not use an output file as was done in wordWrap2.

public static void wordWrap3(Scanner input){ while(input.hasNextLine()){ String line=input.nextLine(); while(line.length()>60){ if (line.charAt(60)==' '){ System.out.println(line.substring(0,60)); line=line.substring(61); }else{ int index=line.substring(0,60).lastIndexOf(" "); System.out.println(line.substring(0,index)); line=line.substring(index+1); } } System.out.println(line); } }

Write a method named coinFlip that accepts as its parameter a Scanner for an input file. Assume that the input file data represents results of sets of coin flips that are either heads (H) or tails (T) in either upper or lower case, separated by at least one space. Your method should consider each line to be a separate set of coin flips and should output to the console the number of heads and the percentage of heads in that line, rounded to the nearest tenth. If this percentage is more than 50%, you should print a "You win" message. For example, consider the following input file: H T H H T T t t T h H h For the input above, your method should produce the following output: 3 heads (60.0%) You win! 2 heads (33.3%) 1 heads (100.0%) You win! The format of your output must exactly match that shown above. You may assume that the Scanner contains at least 1 line of input, that each line contains at least one token, and that no tokens other than h, H, t, or T will be in the lines.

public void coinFlip(Scanner in) { while (in.hasNextLine()) { Scanner line = new Scanner(in.nextLine()); int n = 0; int nh = 0; while (line.hasNext()) { String flip = line.next().toUpperCase(); if (flip.equals("H")) { nh++; } n++; } double ratio = 100.0 * nh / n; System.out.printf("%d heads (%.1f%%)\n", nh, ratio); if (ratio > 50.0) { System.out.println("You win!"); } System.out.println(); } }

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

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

Write a method leetSpeak that accepts two parameters: a Scanner representing an input file, and a PrintStream representing an output file. Your method should convert the input file's text to "leet speak" (aka 1337 speak), an internet dialect where various letters are replaced by other letters/numbers. Output the leet version of the text to the given output file. Preserve the original line breaks from the input. Also wrap each word of input in parentheses. Perform the following replacements: Original character 'Leet' character o 0 l (lowercase L) 1 e 3 a 4 t 7 s (at the end of a word only) Z For example, if the input file lincoln.txt contains the following text: four score and seven years ago our fathers brought forth on this continent a new nation And your method is called in the following way: Scanner input = new Scanner(new File("lincoln.txt")); PrintStream output = new PrintStream(new File("leet.txt")); leetSpeak(input, output); Then after the call, the output file leet.txt should contain the following text: (f0ur) (sc0r3) (4nd) (s3v3n) (y34rZ) (4g0) (0ur) (f47h3rZ) (br0ugh7) (f0r7h) (0n) (7hiZ) (c0n7in3n7) (4) (n3w) (n47i0n) You may assume that each token from the input file is separated by exactly one space. Hint: You may want to use the String object's replace method, which is used as follows: String str = "mississippi"; str = str.replace("s", "*"); // str = "mi**i**ippi"

public void leetSpeak(Scanner input, PrintStream output) { while(input.hasNextLine()) { Scanner line = new Scanner(input.nextLine()); while (line.hasNext()) { String word = line.next(); word = word.replace("o", "0"); word = word.replace("l", "1"); word = word.replace("e", "3"); word = word.replace("a", "4"); word = word.replace("t", "7"); int n = word.length(); if (word.charAt(n-1) == 's') { word = word.substring(0, n-1) + "Z"; } word = "(" + word + ")"; output.print(word + " "); } output.println(); } }

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

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

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

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

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

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

Write a method called stripHtmlTags that accepts a Scanner representing an input file containing an HTML web page as its parameter, then reads that file and prints the file's text with all HTML tags removed. A tag is any text between the characters < and > . For example, consider the following text: <html> <head> <title>My web page</title> </head> <body> <p>There are many pictures of my cat here, as well as my <b>very cool</b> blog page, which contains <font color="red">awesome stuff about my trip to Vegas.</p> Here's my cat now:<img src="cat.jpg"> </body> </html> If the file contained these lines, your program should output the following text: My web page There are many pictures of my cat here, as well as my very cool blog page, which contains awesome stuff about my trip to Vegas. Here's my cat now: You may assume that the file is a well-formed HTML document and that there are no < or > characters inside tags.

public void stripHtmlTags(Scanner input) { while(input.hasNextLine()){ String line=input.nextLine(); while(line.contains("<")||line.contains(">")){ int index1= line.indexOf("<"); int index2=line.indexOf(">"); if(index1==0){ line=line.substring(index2+1); }else{ line=line.substring(0,index1)+line.substring(index2+1); } } System.out.println(line); } }

In physics, a common useful equation for finding the position s of a body in linear motion at a given time t, based on its initial position s0, initial velocity v0, and rate of acceleration a, is the following: s = s0 + v0 t + ½ at2 Write code to declare variables for s0 with a value of 12.0, v0 with a value of 3.5, a with a value of 9.8, and t with a value of 10, and then write the code to compute s on the basis of these values. At the end of your code, print the value of your variable s to the console.

double s0=12.0; double v0=3.5; double a=9.8; int t=10; double s= s0+v0*t+.5*a*t*t; System.out.println(s);

Write for loops to produce the following output: ***** ***** ***** *****

for (int rows=1; rows<=4;rows++){ for (int stars=1; stars<=5; stars++){ System.out.print("*"); } System.out.println(); }

Write for loops to produce the following output: * ** *** **** *****

for (int rows=1;rows<=5; rows++){ for (int stars=1; stars<=rows; stars++){ System.out.print("*"); } System.out.println(); }

Write a method named readEntireFile that accepts a Scanner representing an input file as its parameter, then reads that file and returns the entire text contents of that file as a String.

public String readEntireFile(Scanner in) { String content =""; while (in.hasNextLine()) { content += in.nextLine(); content += "\n"; } return content; }

It's common to print a rotating, increasing list of single-digit numbers at the start of a program's output as a visual guide to number the columns of the output to follow. With this in mind, write nested for loops to produce the following output, with each line 60 characters wide: | | | | | | 123456789012345678901234567890123456789012345678901234567890

for (int i=1;i<=6;i++){ for (int j=1;j<=9;j++){ System.out.print(" "); } System.out.print("|"); } System.out.println(); for (int k=1;k<=6;k++){ System.out.print("1234567890"); }

Write nested for loops to produce the following output: 1 2 3 4 5

for (int row =1; row<=5;row++){ for (int number=4; number>=row; number--){ //starting # of spaces System.out.print(" "); } System.out.println(row); }

Write for loops to produce the following output: 1 22 333 4444 55555 666666 7777777

for (int row=1; row <=7;row++){ for (int number=1; number<=row;number++){ System.out.print(row); } System.out.println(); }

Write nested for loops to produce the following output: 1 22 333 4444 55555

for (int row=1; row<=5; row++){ for (int number =5; number>row; number--){ System.out.print(" "); } for (int k=1; k<=row;k++){ System.out.print(row); } System.out.println(); }

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

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

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

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

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

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

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

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

Write a method named negativeSum that accepts a Scanner as a parameter reading input from a file containing a series of integers, and determine whether the sum starting from the first number is ever negative. The method should print a message indicating whether a negative sum is possible and should return true if a negative sum can be reached and false if not. For example, if the file contains the following text, your method will consider the sum of just one number (38), the sum of the first two numbers (38 + 4), the sum of the first three numbers (38 + 4 + 19), and so on up to the sum of all of the numbers: 38 4 19 -27 -15 -3 4 19 38 None of these sums is negative, so the method would produce the following message and return false: no negative sum If the file instead contains the following numbers, the method finds that a negative sum of -8 is reached after adding 6 numbers together (14 + 7 + -10 + 9 + -18 + -10): 14 7 -10 9 -18 -10 17 42 98 It should output the following and return true, indicating that a negative sum can be reached: -8 after 6 steps

public boolean negativeSum(Scanner in) { int step =0; int sum = 0; boolean flag = false; while (in.hasNextInt()) { sum+= in.nextInt(); step++; if (sum < 0) { flag = true; break; } } if (flag) { System.out.println(sum + " after " + step + " steps"); } else { System.out.println("no negative sum"); } return flag; }

Write a complete program in a class named CollegeAdmit that uses a Scanner to read user input for a student's grade point average and SAT exam score, and uses these values to decide whether the student is admitted to the university. A GPA below 1.8 will cause the student to be rejected; an SAT score below 900 will also cause a rejection. Otherwise the student is accepted. If both the GPA and the SAT score are too low, print the message about the GPA being too low. Your output should match the following examples: University admission program What is your GPA? 3.2 What is your SAT score? 1280 You were accepted! University admission program What is your GPA? 3.95 What is your SAT score? 860 Your SAT score is too low. University admission program What is your GPA? 1.4 What is your SAT score? 1590 Your GPA is too low.

public class CollegeAdmit{ public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("University admission program"); System.out.print("What is your GPA? "); double gpa = console.nextDouble(); System.out.print("What is your SAT score? "); int sat = console.nextInt(); if (gpa < 1.8) { System.out.println("Your GPA is too low."); } else if (sat < 900) { System.out.println("Your SAT score is too low."); } else { System.out.println("You were accepted!"); } } }

Write a complete Java program in a class named Difference that prints the following output: What is the difference between a ' and a "? Or between a " and a \"? One is what we see when we're typing our program. The other is what appears on the "console."

public class Difference { public static void main (String[]args) { System.out.println("What is the difference between"); System.out.println("a ' and a \"? Or between a \" and a \\\"?"); System.out.println(""); System.out.println("One is what we see when we're typing our program."); System.out.println("The other is what appears on the \"console.\""); } }

Write a complete Java program in a class named Egg2 that generates the following output. Use static methods to show structure and eliminate redundancy in your solution. _______ / \ / \ \ / \_______/ -"-'-"-'-"- _______ / \ / \ \ / \_______/ -"-'-"-'-"- \ / \_______/ _______ / \ / \ -"-'-"-'-"- \ / \_______/

public class Egg2 { public static void main(String[]args) { Line1(); Line2(); Line3(); Line4(); Line5(); Line6(); Line1(); Line2(); Line3(); Line4(); Line5(); Line6(); Line4(); Line5(); Line1(); Line2(); Line3(); Line6(); Line4(); Line5(); } public static void Line1(){ System.out.println(" _______"); } public static void Line2(){ System.out.println(" / \\"); } public static void Line3(){ System.out.println("/ \\"); } public static void Line4(){ System.out.println("\\ /"); } public static void Line5(){ System.out.println(" \\_______/"); } public static void Line6(){ System.out.println("-\"-'-\"-'-\"-"); } }

Write a complete Java program in a class named EggStop that generates the following output. Use static methods to show structure and eliminate redundancy in your solution. ______ / \ / \ \ / \______/ ______ / \ / \ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ +--------+

public class EggStop{ public static void main(String[]args){ line1(); line2(); line3(); line4(); line5(); blank(); line1(); line2(); line3(); line4(); line5(); plus(); blank(); line1(); line2(); line3(); stop(); line4(); line5(); plus(); } public static void line1(){ System.out.println(" ______"); } public static void line2(){ System.out.println(" / \\"); } public static void line3(){ System.out.println("/ \\"); } public static void line4(){ System.out.println("\\ /"); } public static void line5(){ System.out.println(" \\______/"); } public static void plus(){ System.out.println("+--------+"); } public static void blank(){ System.out.println(""); } public static void stop(){ System.out.println("| STOP |"); } }

Write a complete Java program in a class named FightSong that generates the following three figures of output. Use static methods to show structure and eliminate redundancy in your solution. In particular, make sure that main contains no System.out.println statements, that any System.out.println statement(s) repeated are captured in a method that is called just once, and that the same System.out.println statement never appears in two places in the code. Go, team, go! You can do it. Go, team, go! You can do it. You're the best, In the West. Go, team, go! You can do it. Go, team, go! You can do it. You're the best, In the West. Go, team, go! You can do it. Go, team, go! You can do it.

public class FightSong{ public static void main(String[]args){ goTeam(); doIt(); blank(); goTeam(); doIt(); best(); west(); goTeam(); doIt(); blank(); goTeam(); doIt(); best(); west(); goTeam(); doIt(); blank(); goTeam(); doIt(); } public static void goTeam(){ System.out.println("Go, team, go!"); } public static void doIt (){ System.out.println("You can do it."); } public static void blank(){ System.out.println(""); } public static void best(){ System.out.println("You're the best,"); } public static void west(){ System.out.println("In the West."); } }

Write a complete Java program in a class named Lanterns that generates the following three figures of output. Use static methods to show structure and eliminate redundancy in your solution. In particular, make sure that main contains no System.out.println statements, that any System.out.println statement(s) repeated are captured in a method that is called just once, and that the same System.out.println statement never appears in two places in the code. ***** ********* ************* ***** ********* ************* * | | | | | * ************* ***** ********* ************* ***** ********* ************* ***** * | | | | | * * | | | | | * ***** *****

public class Lanterns{ public static void main (String[]args){ S5(); S9(); S13(); blank(); S5(); S9(); S13(); Lines(); S13(); S5(); S9(); S13(); blank(); S5(); S9(); S13(); S5(); Lines(); Lines(); S5(); S5(); } public static void S5(){ System.out.println(" *****"); } public static void S9(){ System.out.println(" *********"); } public static void S13(){ System.out.println("*************"); } public static void Lines(){ System.out.println("* | | | | | *"); } public static void blank(){ System.out.println(""); } }

Write a complete Java program in a class named Mantra that produces the following output. Remove its redundancy by adding a method. There's one thing every coder must understand: The System.out.println command. There's one thing every coder must understand: The System.out.println command.

public class Mantra{ public static void main(String[] args){ OneThing(); System(); Blank(); OneThing(); System(); } public static void OneThing(){ System.out.println("There's one thing every coder must understand:"); } public static void Blank (){ System.out.println(""); } public static void System(){ System.out.println("The System.out.println command."); } }

Write a complete Java program called Meta whose output is the text that would be the source code of a Java program named Hello that prints "Hello, world!" as its output: public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } } Your program must produce exactly the output shown in order to pass (using exactly four spaces for each increment of indentation in the output).

public class Meta { public static void main(String[] args) { System.out.println("public class Hello {"); System.out.println (" public static void main(String[] args) {"); System.out.println(" System.out.println(\"Hello, world!\");"); System.out.println(" }"); System.out.println("}"); } }

Write a complete Java program in a class named MuchBetter that prints the following output: A "quoted" String is 'much' better if you learn the rules of "escape sequences." Also, "" represents an empty String. Don't forget: use \" instead of " ! '' is not the same as "

public class MuchBetter{ public static void main (String[] args) { System.out.println("A \"quoted\" String is"); System.out.println("'much' better if you learn"); System.out.println("the rules of \"escape sequences.\""); System.out.println("Also, \"\" represents an empty String."); System.out.println("Don't forget: use \\\" instead of \" !"); System.out.println(" ' ' is not the same as \""); } }

Write a program in a class named Shining that prints the following line of output 1000 times: All work and no play makes Jack a dull boy. You should not write a program whose source code is 1000 lines long; use methods to shorten the program. What is the shortest program you can write that will produce the 1000 lines of output, using only the material from Chapter 1 (println, methods, etc.)?

public class Shining{ public static void main(String[]args){ work(); } public static void work(){ for(int p=1; p<=1000; p++){ System.out.println("All work and no play makes Jack a dull boy."); } } }

Write a Java program in a class named SlashFigure that produces the following output. Use nested for loops to capture the structure of the figure. (If you previously solved Self-Check problems 34 and 35 in the book, you will have created a loop table that will be useful in solving this problem. Use it!) !!!!!!!!!!!!!!!!!!!!!! \\!!!!!!!!!!!!!!!!!!// \\\\!!!!!!!!!!!!!!//// \\\\\\!!!!!!!!!!////// \\\\\\\\!!!!!!//////// \\\\\\\\\\!!//////////

public class SlashFigure { public static void main(String[] args) { for (int rows=1; rows<=6; rows++){ for (int slashes=1; slashes <= 2*rows-2;slashes++){ System.out.print("\\"); } for (int point=1; point <=-4*rows+26 ;point++){ System.out.print("!"); } for (int slashes=1; slashes <= 2*rows-2;slashes++){ System.out.print("/"); } System.out.println(); } } }

Write a complete Java program in a class named StarFigures that generates the following output. Use static methods to show structure and eliminate redundancy in your solution. ***** ***** * * * * * ***** ***** * * * * * ***** ***** * * * ***** ***** * * * * *

public class StarFigures{ public static void main(String[]args){ S5(); S5(); S2(); S1(); S2(); blank(); S5(); S5(); S2(); S1(); S2(); S5(); S5(); blank(); S1(); S1(); S1(); S5(); S5(); S2(); S1(); S2(); } public static void S5(){ System.out.println("*****"); } public static void S2(){ System.out.println(" * * "); } public static void S1(){ System.out.println(" * "); } public static void blank(){ System.out.println(""); } }

Write a complete Java program in a class named Stewie that prints the following output: ////////////////////// || Victory is mine! || \\\\\\\\\\\\\\\\\\\\\\

public class Stewie { public static void main(String[] args) { System.out.println("//////////////////////"); System.out.println("|| Victory is mine! ||"); System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"); } }

Write a complete Java program in a class named Stewie2 that prints the following output. Use at least one static method besides main to remove redundancy. ////////////////////// || Victory is mine! || \\\\\\\\\\\\\\\\\\\\\\ || Victory is mine! || \\\\\\\\\\\\\\\\\\\\\\ || Victory is mine! || \\\\\\\\\\\\\\\\\\\\\\ || Victory is mine! || \\\\\\\\\\\\\\\\\\\\\\ || Victory is mine! || \\\\\\\\\\\\\\\\\\\\\\

public class Stewie2 { public static void main(String[]args){ Forward(); Victory(); Back(); Victory(); Back(); Victory(); Back(); Victory(); Back(); Victory(); Back(); } public static void Forward(){ System.out.println("//////////////////////"); } public static void Victory(){ System.out.println("|| Victory is mine! ||"); } public static void Back(){ System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"); } }

Write a complete Java program in a class named TwoRockets that generates the following output. Use static methods to show structure and eliminate redundancy in your solution. Note that there are two rocket ships next to each other. What redundancy can you eliminate using static methods? What redundancy cannot be eliminated? /\ /\ / \ / \ / \ / \ +------+ +------+ | | | | | | | | +------+ +------+ |United| |United| |States| |States| +------+ +------+ | | | | | | | | +------+ +------+ /\ /\ / \ / \ / \ / \

public class TwoRockets{ public static void main(String[]args){ cone(); box(); unitedStates(); box(); cone(); } public static void cone(){ System.out.println(" /\\ /\\"); System.out.println(" / \\ / \\"); System.out.println(" / \\ / \\"); } public static void box(){ System.out.println("+------+ +------+"); System.out.println("| | | |"); System.out.println("| | | |"); System.out.println("+------+ +------+"); } public static void unitedStates(){ System.out.println("|United| |United|"); System.out.println("|States| |States|"); } }

Write a complete Java program in a class named WellFormed that prints the following output: A well-formed Java program has a main method with { and } braces. A System.out.println statement has ( and ) and usually a String that starts and ends with a " character. (But we type \" instead!)

public class WellFormed { public static void main(String[]args){ System.out.println("A well-formed Java program has"); System.out.println("a main method with { and }"); System.out.println("braces."); System.out.println(""); System.out.println("A System.out.println statement"); System.out.println("has ( and ) and usually a"); System.out.println("String that starts and ends "); System.out.println("with a \" character."); System.out.println("(But we type \\\" instead!)"); } }

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 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 word, int totalLength) { int len=word.length(); if (totalLength <= len) return(word); for (int i=0; i<(totalLength-len); i++) { word = " " + word; } return(word); }

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 static method named collapseSpaces that accepts a Scanner representing a file as a parameter and writes that file's text to the console, with multiple spaces or tabs reduced to single spaces between words that appear on the same line. For example, if a Scanner variable named input is reading an input file containing the following text: four score and seven years ago our fathers brought forth on this continent a new nation then the call collapseSpaces(input); should produce the following output: four score and seven years ago our fathers brought forth on this continent a new nation

public static void collapseSpaces(Scanner in) { String line, outline; Scanner line_in; while(in.hasNextLine()) { line = in.nextLine(); line_in = new Scanner(line); outline = ""; while (line_in.hasNext()) { outline += line_in.next(); outline += " "; } System.out.println(outline); } }

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

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

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

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

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 c){ int min=Math.min(Math.min(a,b),c); double middle=(a+b+c)/3.0; int max=Math.max(Math.max(a,b),c); return (max-middle==middle-min); }

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

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

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 radius){ return (Math.PI*radius*radius); }

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 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 pay, int hours){ int overtime=hours-8; double salary =hours*pay; if (overtime>0){ salary=salary+.5*pay*overtime; } return(salary); }

Write a method named doubleSpace that accepts a Scanner for an input file and a PrintStream for an output file as its parameters, writing into the output file a double-spaced version of the text in the input file. You can achieve this task by inserting a blank line between each line of output.

public static void doubleSpace(Scanner Input, PrintStream out){ while(Input.hasNextLine()){ out.println(Input.nextLine()); out.println(); } }

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

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. The formula for the volume of a sphere with radius r is the following: volume = 4/3 π r3

public static double sphereVolume(double radius){ return 4.0/3*Math.PI*(radius*radius*radius); }

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. The formula is based on the computed value s, a length equal to half the perimeter of the triangle: area = √ (s (s-a)(s-b)(s-c)) where s = (a + b + c) / 2

public static double triangleArea(double a, double b, double c){ double s=(a+b+c)/2; return Math.sqrt(s*(s-a)*(s-b)*(s-c)); }

Write a method named firstDigit that returns the first digit of an integer. For example, firstDigit(3572) should return 3. It should work for negative numbers as well. For example, firstDigit(-947) should return 9. Call Value Returned firstDigit(3572) 3 firstDigit(-947) 9 firstDigit(6) 6 firstDigit(35) 3 firstDigit(123456) 1

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

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 x, int y){ return Math.max(Math.abs(x), Math.abs(y)); }

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

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

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 word){ StringTokenizer=new StringTokenizer (word); int count=tok.countTokens(); return count; }

Write a method named boyGirl that accepts a Scanner as a parameter. The Scanner is reading its input from a file containing a series of names followed by integers. The names alternate between boys' names and girls' names. Your method should compute the absolute difference between the sum of the boys' integers and the sum of the girls' integers. The input could end with either a boy or girl; you may not assume that it contains an even number of names. If the input file tas.txt contains the following text: Steve 3 Sylvia 7 Craig 14 Lisa 13 Brian 4 Charlotte 9 Jordan 6 then your method could be called in the following way: Scanner input = new Scanner(new File("tas.txt")); boyGirl(input); and should produce the following output, since the boys' sum is 27 and the girls' sum is 29: 4 boys, 3 girls Difference between boys' and girls' sums: 2

public static void boyGirl (Scanner input){ int boySum=0; int boys=0; int girlSum=0; int girls=0; int count=0; while(input.hasNextLine()){ if(count==0){ boys++; input.next(); boySum+=input.nextInt(); count++; }else{ girls++; input.next(); girlSum+=input.nextInt(); count=0; } } System.out.println(boys+" boys, "+girls+" girls"); System.out.println("Difference between boys' and girls' sums: "+(Math.abs(boySum-girlSum))); }

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); These calls should produce the following output: 1 2 4 8 1 2 4 8 16 32 64 128 256 512 1024

public static void printPowersOf2 (int n){ int ans =1; for (int i=0; i<= n; i++){ System.out.print(ans + " "); ans=ans*2; } 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. Here is an example dialogue with the user: On what day of the month were you born? 8 What is the name of the month in which you were born? May During what year were you born? 1981 You were born on May 8, 1981. You're mighty old!

public static void inputBirthday(Scanner console){ System.out.print("On what day of the month were you born? "); int day=console.nextInt(); System.out.print("What is the name of the month in which you were born? "); String month=console.next(); System.out.print("During what year were you born? "); int year=console.nextInt(); System.out.println("You were born on "+month+" "+day+", "+year+"."+" 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: 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 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. Here are some example calls to your method and their expected results: Call: printGrid(3, 6); printGrid(5, 3); printGrid(4, 1); printGrid(1, 3); Output: 1, 4, 7, 10, 13, 16 2, 5, 8, 11, 14, 17 3, 6, 9, 12, 15, 18 1, 6, 11 2, 7, 12 3, 8, 13 4, 9, 14 5, 10, 15 1 2 3 4 1,

public static void printGrid(int rows, int cols) { for(int lines=1;lines<=rows;lines++){ int x=lines; for(int number=lines;number<cols+lines-1;number++){ System.out.print(x+", "); x+=rows; } System.out.print(x); System.out.println(); } }

Write a method called printNumbers that accepts a maximum number as a parameter and prints each number from 1 up to that maximum, inclusive, boxed by square brackets. For example, consider the following calls: printNumbers(15); printNumbers(5); These calls should produce the following output: [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [1] [2] [3] [4] [5]

public static void printNumbers(int n) { for(int i=1; i<=n;i++){ System.out.print("[" + i + "] "); } }

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 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); These calls should produce the following output: 1 4 16 64 1 5 25 125 625 3125 15625 1 -2 4 -8 16 -32 64 -128 256

public static void printPowersOfN(int x, int y){ for (int i=0; i<=y;i++){ System.out.print((int)Math.pow(x, i)); System.out.print(" "); } }

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

public static void printReverse(String phrase) { for (int i=phrase.length()-1; i>=0; i--) { System.out.print(phrase.charAt(i)); } } public static void printReverse(String phrase) { for (int i=0;i<=phrase.length()-1;i++) { System.out.print(phrase.charAt(phrase.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. Call printSquare(1, 5); printSquare(3, 9); printSquare(0, 3); printSquare(5, 5); Output 12345 23451 34512 45123 51234 3456789 4567893 5678934 6789345 7893456 8934567 9345678 0123 1230 2301 3012 5

public static void printSquare(int min, int max) { for (int row=min;row<=max;row++){ for (int a=row; a<=max;a++){ System.out.print(a); } int c=min; for (int b=1;b<=row-min;b++){ System.out.print(c); c++; } System.out.println(); } }

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. Here is a sample dialogue with the user: Please enter your full name: Sammy Jankis Your name in reverse order is Jankis, Sammy

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

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. The formula for solving a quadratic equation is: quadratic equation Here are some example equations and their roots: equation x2 - 7x + 12 x2 + 3x + 2 call quadratic(1, -7, 12); quadratic(1, 3, 2); output First root = 4.0 Second root = 3.0 First root = -1.0 Second root = -2.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 x = Math.sqrt(b*b - 4* a* c); double y = (-b + x)/(2*a); double z = (-b - x)/(2*a); System.out.println("First root = " + y); System.out.println("Second root = " + z); }

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

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

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

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

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

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

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

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); Output xooox oxoxo ooxoo oxoxo xooox xoooooox oxooooxo ooxooxoo oooxxooo oooxxooo ooxooxoo oxooooxo xoooooox xox oxo xox x xoooooooooox oxooooooooxo ooxooooooxoo oooxooooxooo ooooxooxoooo oooooxxooooo oooooxxooooo ooooxooxoooo oooxooooxooo ooxooooooxoo oxooooooooxo xoooooooooox xooooooooox oxoooooooxo ooxoooooxoo oooxoooxooo ooooxoxoooo oooooxooooo ooooxoxoooo oooxoooxooo ooxoooooxoo oxoooooooxo xooooooooox

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 named countCoins that accepts as its parameter a Scanner for an input file whose data represents a person's money grouped into stacks of coins. Your method should add up the cash values of all the coins and print the total money at the end. The input consists of a series of pairs of tokens, where each pair begins with an integer and is followed by the type of coin, which will be either "pennies" (1 cent each), "nickels" (5 cents each), "dimes" (10 cents each), or "quarters" (25 cents each), case-insensitively. A given coin might appear more than once on the same line. For example, if the input file contains the following text: 3 pennies 2 quarters 1 pennies 3 nickels 4 dimes 3 pennies are worth 3 cents, and 2 quarters are worth 50 cents, and 1 penny is worth 1 cent, and 3 nickels are worth 15 cents, and 4 dimes are worth 40 cents. The total of these is 1 dollar and 9 cents, therefore your method would produce the following output if passed this input data. Notice that the method should show exactly two digits after the decimal point, so it says 09 for 9 cents: Total money: $1.09 Here is a second example. Suppose the input file contains the following text. Notice the capitalization and spacing: 12 QUARTERS 1 Pennies 33 PeNnIeS 10 niCKELs Then your method would produce the following output: Total money: $3.84

public void countCoins(Scanner in) { int sum = 0; int n = 0; String unit=""; while(in.hasNext()) { if (in.hasNextInt()) { n = in.nextInt(); } else { unit = in.next(); unit = unit.toLowerCase(); if (unit.equals("pennies")) { sum += n; } else if (unit.equals("nickels")) { sum += n * 5; } else if (unit.equals("dimes")) { sum += n * 10; } else if (unit.equals("quarters")){ sum += n * 25; } else { } } } System.out.printf("Total money: $%.2f", 0.01 * sum); }

Write a method named evenNumbers that accepts a Scanner as a parameter reading input from a file containing a series of integers, and report various statistics about the integers. You may assume that there is at least one integer in the file. Report the total number of numbers, the sum of the numbers, the count of even numbers and the percent of even numbers. For example, if a Scannerinput on file numbers.txt contains the following text: 5 7 2 8 9 10 12 98 7 14 20 22 then the call evenNumbers(input); should produce the following output: 12 numbers, sum = 214 8 evens (66.67%)

public void evenNumbers(Scanner input) { int n = 0; int sum = 0; int ne = 0; int num; while (input.hasNextInt()) { num = input.nextInt(); n++; sum += num; if (num % 2 == 0) { ne++; } } System.out.println(n + " numbers, sum = " + sum); System.out.printf("%d evens (%.2f%%)", ne, 100.0*ne/n); }

Write a method named flipLines that accepts as its parameter a Scanner for an input file and that writes to the console the same file's contents with successive pairs of lines reversed in order. For example, if the input file contains the following text: Twas brillig and the slithy toves did gyre and gimble in the wabe. All mimsey were the borogroves, and the mome raths outgrabe. "Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch." The program should print the first pair of lines in reverse order, then the second pair in reverse order, then the third pair in reverse order, and so on. Therefore your method should produce the following output to the console: did gyre and gimble in the wabe. Twas brillig and the slithy toves and the mome raths outgrabe. All mimsey were the borogroves, "Beware the Jabberwock, my son, Beware the JubJub bird and shun the jaws that bite, the claws that catch, the frumious bandersnatch." Notice that a line can be blank, as in the third pair. Also notice that an input file can have an odd number of lines, as in the one above, in which case the last line is printed in its original position. You may not make any assumptions about how many lines are in the Scanner.

public void flipLines(Scanner in) { String line1, line2; while (in.hasNextLine()) { line1 = in.nextLine(); if (in.hasNextLine()) { line2 = in.nextLine(); System.out.println(line2); } System.out.println(line1); } }

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


Related study sets

Mastering Biology Questions Chapter 6 (Exam 2)

View Set

PRESENT SIMPLE OR PRESENT CONTINUOUS? (Gap-fill)

View Set

Government Unit 1 Lesson 2 Part 2

View Set

Insights 8 Glossary: Multicultural issues

View Set

Macroeconomics 2.01: The Circular Flow and GDP

View Set

MGW1010 Week 6 Managing Organisational Design

View Set

The 12 Stages of The Hero's Journey

View Set