Final Exam Preparation


Part 1:

Final Review

Answer Key




Assignment 20.1: Barnyard Animals (10 pts)
  • Create a Java file named Animals.java
  • Then, create three text files to be used in the program: nums.txt, animals.txt and outfile.txt
  • Right-click the Animals project folder and select New->File. Name your file nums.txt.
  • Important: Make sure that you did not accidentally save your file under the src folder. If you did, you can simply drag and drop it into the main project folder.
  • Here are the values to place in the nums.txt file:
5
3
8
2
4
  • Next, create a second file called animals.txt.
  • Copy the following data into the that file:
chickens
cows
ducks
horses
pigs
  • Follow a similar process to create a blank text file named outfile.txt.
  • Add the following import statement to the top of your program
    import java.io.*;
    
  • Alter the signature of main() as required for File I/O (see lesson notes if you are unsure).
  • Then, declare a new file object for the nums.txt input file, and a new Scanner to read in from this file
  • Next, declare a second file object for the animals.txt input file, and a new Scanner to read from this file
  • Finally, declare a File and PrintWriter object to write to outfile.txt.
  • Below your code for the file I/O, declare two arrays of size 5 as follows:
    • one array contains Strings and is named animals
    • one array contains ints and is named number_animals
  • Assign the data in animals.txt to the animals array by reading the data from the file, and assigning each data point to one index in the array.
  • Hint: you can use 5 input.next() statements, or use a for loop (better approach). For example:
animals[0] = input.next();
  • Also, assign values to the number_animals array by reading in those values from the nums.txt file. For example:
    number_animals[0] = input.nextInt();
    
  • Now it is time to write to the file. Print a header as follows:
    out.println("Animals at our farm");
    
  • Then, write a for loop to write the contents of the two arrays to outfile.txt
  • When you are finished, outfile.txt should contains the following:
Animals at our farm
5 chickens
3 cows
8 ducks
2 horses
4 pigs
  • Once it is giving the correct output, submit Animals.java to Canvas.


Assignment 20.2: Arrays and Methods Worksheet 2 (10 pts)

  • Copy the following into a new file called ArrayMethods2.java.
  • update here
  • Write the methods one-by-one. Compile and run your code after you write each method to make sure it was written properly.
  • When your methods pass all of the tests, upload your file to Canvas.
/**
 * Assignment 20.2
 * @author Your Name
 * CIS 36A
 */
public class ArrayMethods2 {

    /**
    * Given an array of ints, return the index of the first appearance of the
    * number 42. If not found return -1.
    * @param data array of ints
    * @return the index of the first number 42, -1 if not found.
    * Test cases:
    * findFirst42({1, 1, 42, 3, 1}) --> 2
    * findFirst42({1, 1, 2, 42, 1}) --> 3
    * findFirst42({1, 1, 2, 1, 2, 3}) --> -1
    */
    public static int findFirst42(int[] data) {
       
        return -1;
    }

    /**
     * Given an array of ints, return true if
     * the sequence .. 1, 2, 3, .. appears
     * in the array somewhere.
     * @param data array of ints
     * @return true if .. 1, 2, 3, .. appears in the array,
     * false otherwise.
     * Test cases:
     * is123({1, 2, 3, 1}) --> true
     * is123({1, 2, 4, 1}) --> false
     * is123({1, 2, 1, 2, 3}) --> true
     */
    public static boolean is123(int[] data) {
       
        return false;
    }

    /**
     * Prints all the elements in an array to the console
     * on one line with a space between each element.
     * @param data The array to print.
     */
    public static void printArray(int[] data) {
       
        System.out.println();
    }

    /**
     * Given an array of ints, delete first appearance of the number 42.
     * By replacing it with a 0.
     * If the number does not exist in the array, leave the array unchanged.
     * @param data array of ints
     * Hint: use return; to end the method early!
     * Test cases:
     * eraseFirst42({1, 2, 42, 3, 1}) --> {1, 2, 0, 3, 1}
     * eraseFirst42({1, 2, 3, 42, 42, 1}) --> {1, 2, 3, 0, 42, 1}
     * eraseFirst42({1, 2, 3}) --> {1, 2, 3}
     */
    public static void eraseFirst42(int[] data) {
        return;
    }



    public static void main(String[] args) {
        boolean answer = false;
        int num = 0;
       
        System.out.println("***Testing findFirst42***");
        final int A3 = 3, A42 = 42;
        int[] data1 = {1, 2, A42, A3, 1};
        num = findFirst42(data1);
        System.out.println("findFirst42a should be 2: " + num);
        int[] data2 = {1, 1, 2, A42, 1};
        num = findFirst42(data2);
        System.out.println("findFirst42a should be 3: " + num);
        int[] data3 = {1, 1, 2, 1, 2};
        num = findFirst42(data3);
        System.out.println("findFirst42a should be -1: " + num);

        System.out.println("\n***Testing is123***");
        final int A4 = 4;
        int[] data4 = {1, 2, A3, 1};
        answer = is123(data4);
        System.out.println("is123a should be true: " + answer);
        int[] data5 = {1, 2, A4, 1};
        answer = is123(data5);
        System.out.println("is123a should be false: " + answer);
        int[] data6 = {1, 2, 1, 2, A3};
        answer = is123(data6);
        System.out.println("is123a should be true: " + answer);
   
        System.out.println("\n***Testing printArray***");
        System.out.println("printArray1 should be 1 2 3 1: ");
        printArray(data4);
        System.out.println("printArray2 should be 1 2 4 1: ");
        printArray(data5);
        final int A7 = 7;
        int[] data7 = {A7};
        System.out.println("printArray1 should be 7: ");
        printArray(data7);
  
        System.out.println("\n***Testing eraseFirst42***");
        eraseFirst42(data1);
        System.out.println("eraseFirst42a should be 1 2 0 3 1: ");
        printArray(data1);
        int[] data8 = {1, 2, A3, A42, A42, 1};
        eraseFirst42(data8);
        System.out.println("eraseFirst42b should be 1 2 3 0 42 1: ");
        printArray(data8);
        int[] data9 = {1, 2, A3};
        eraseFirst42(data9);
        System.out.println("eraseFirst42c should be 1 2 3: ");
        printArray(data9);
   
        System.out.print("\n***End of Tests***");

    }
}


Assignment 20.3: NASA Temperature Data (10 pts)

  • In this assignment we will work with a real data set from climate.NASA.gov
  • One of NASA's important roles is to track Climate Change.
  • NASA records data related to average yearly temperatures, monthly atmospheric carbon dioxide levels, changes in sea ice, and sea levels.
  • The purpose of this program will be to search the data set for the years with smallest and largest average temperatures, and to write these years into a file.
  • Create a new project folder called Climate with a new Java file named Climate.java.
  • Copy and paste the below starter code into Climate.java:

/**
 * @author YOUR NAME HERE
 * CIS 36A
 */

//add import statement(s) here
import java.util.Scanner;

public class Climate {
    public static void main(String[] args) { //throw exception here
       
int min_index, max_index;
        final int ARRAY_LENGTH = 139;
    
        //declare arrays here
       
        //declare File variables here
        //declare Scanner variable here
        //declare PrintWriter variable here
       
        //write for loop here to read in data from file to two arrays
       
        //call the two methods:
        //min_index = //call findMin
        //max_index = //call findMax
       
        //replace below statements to write to file instead of console
        System.out.println("The hottest year since 1880 is " + years[max_index]);
        System.out.println("The coldest year since 1880 is " + years[min_index]);
       
        //don't forget to close Scanner and PrintWriter!
    }
}
  • Next we need two text files
  • Right-click the Climate project folder and select New->File. Name your file globalTemperatures.txt
  • Make sure that you did not accidentally save your file under the src folder. If you did, you can simply drag and drop it into the main Climate project folder.
  • Then, create a second (empty) text file called output.txt using the same approach.
  • Copy and paste the below data into globalTemperatures.txt:
1880    -0.19
1881    -0.10
1882    -0.11
1883    -0.19
1884    -0.28
1885    -0.31
1886    -0.32
1887    -0.35
1888    -0.18
1889    -0.11
1890    -0.37
1891    -0.23
1892    -0.26
1893    -0.31
1894    -0.31
1895    -0.22
1896    -0.11
1897    -0.12
1898    -0.27
1899    -0.18
1900    -0.09
1901    -0.15
1902    -0.28
1903    -0.38
1904    -0.48
1905    -0.28
1906    -0.22
1907    -0.39
1908    -0.43
1909    -0.47
1910    -0.42
1911    -0.43
1912    -0.35
1913    -0.35
1914    -0.15
1915    -0.12
1916    -0.33
1917    -0.44
1918    -0.28
1919    -0.26
1920    -0.26
1921    -0.18
1922    -0.28
1923    -0.25
1924    -0.26
1925    -0.21
1926    -0.09
1927    -0.20
1928    -0.19
1929    -0.34
1930    -0.14
1931    -0.09
1932    -0.16
1933    -0.28
1934    -0.14
1935    -0.20
1936    -0.16
1937    -0.04
1938    -0.03
1939    -0.03
1940    0.12
1941    0.18
1942    0.05
1943    0.07
1944    0.21
1945    0.09
1946    -0.07
1947    -0.04
1948    -0.10
1949    -0.11
1950    -0.18
1951    -0.07
1952    0.01
1953    0.07
1954    -0.14
1955    -0.14
1956    -0.20
1957    0.04
1958    0.07
1959    0.03
1960    -0.02
1961    0.06
1962    0.04
1963    0.07
1964    -0.20
1965    -0.10
1966    -0.05
1967    -0.02
1968    -0.07
1969    0.07
1970    0.03
1971    -0.09
1972    0.01
1973    0.16
1974    -0.08
1975    -0.02
1976    -0.11
1977    0.17
1978    0.06
1979    0.16
1980    0.27
1981    0.33
1982    0.13
1983    0.31
1984    0.16
1985    0.12
1986    0.18
1987    0.33
1988    0.41
1989    0.28
1990    0.44
1991    0.41
1992    0.22
1993    0.24
1994    0.31
1995    0.44
1996    0.33
1997    0.47
1998    0.62
1999    0.39
2000    0.40
2001    0.53
2002    0.62
2003    0.60
2004    0.53
2005    0.67
2006    0.62
2007    0.64
2008    0.51
2009    0.63
2010    0.70
2011    0.57
2012    0.62
2013    0.65
2014    0.73
2015    0.87
2016    0.99
2017    0.90
2018    0.82

  • Note that the first column above represents the year, and the second column represents the change in global surface temperature relative to 1951-1980 average temperatures (without smoothing)
  • You can find this data set online here.
  • Next, create two arrays of length 139 - one a String array named years, and one a double array named temperatures.
    • NASA has tracked yearly temperatures changes for 139 years
  • Using a for loop, read in the above data into the two arrays.
  • Note that you should use only one for loop.
    • Inside this for loop, alternate reading the data into each array, starting with the String array for the year.
    • Recall that for the String array, you will use input.next() and for the integer array, you will use input.nextInt().
  • For an example of reading data into an array using a for loop, please see the Lesson 19 notes, the example entitled: Example Program Using Arrays to Collect and Display Data Items
  • Next, add two methods to your program:
/**
* Searches an array for the location of the minimum value
* @param array, an array of doubles
* @return the index where the minimum value is located
*/
public static int findMin(double[] array) {
    double min = Double.MAX_VALUE; //largest possible double stored as a variable
           int min_index = -1;
    //fill in the rest of the method body here
    return min_index;
}


/**
* Searches an array for the location of the maximum value
* @param array, an array of doubles
* @return the index where the maximum value is located
*/
public static int findMax(double[] array) {
    double max = Double.MIN_VALUE; //smallest possible double stored as a variable
    int max_index = -1;
 //fill in the rest of the method body here
return max_index;
}
  • Implement the method bodies according to the description in the Javadoc comment and also using the method information below:
findMin Method:
  • This method takes an array of doubles as a parameter
  • It initializes a variable named min to be a large number (largest possible double)
  • It initializes a second variable min_index to be -1
  • Then, uses a for loop to step through the array
  • At each index in the array, it compares the double stored at that index to the min
  • If the double stored at index i is smaller than min, it assigns min to be array[i]
  • It will also assign min_index to be i
  • It returns min_index
findMax Method:
  • This method takes an array of doubles as a parameter
  • It initializes a variable named max to be a small number (smallest possible double)
  • It initializes a second variable max_index to be -1
  • Then, uses a for loop to step through the array
  • At each index in the array, it compares the double stored at that index to the max
  • If the double stored at index i is bigger than max, it assigns max to be array[i]
  • It will also assign max_index to be i
  • It returns max_index
  • Note that these methods implement the second algorithm that you wrote for Assignment 2.1: Two Algorithms, at the beginning of the quarter.
  • Now, inside of main, call the two methods to find the years with the highest and lowest average temperatures.
  • Once you have that information, write it into output.txt.
  • Your output.txt should contain the following output when you are finished:
The hottest year since 1880 is 2016
The coldest year since 1880 is 1904

  • When your program is giving the correct output, upload Climate.java to Canvas.



Assignment 14.1: Java Jive, Part 2 (10 pts)

  • Encoding and decoding information can save memory space and speed transmission of data.
  • Businesses often encode orders to reduce writing and speed up customer orders.
  • In this assignment, we will look at decoding orders for a coffee and pastry company, called Java Jive Cafe and Bakery.
  • Write a program (Cafe.java) that prompts the user for a single input where the first one or two characters is a flavor of coffee or tea in the following shorthand code, and the last characters is the serving size.

Code Drink Variety
CA
Cafe Americano
CAL
Chai Latte
CAP
Capuccino
DCDrip Coffee
DESDouble Espresso
MLMatcha Latte
SES
Single Espresso
TEA
Tea
 TL Turmeric Latte

  • For example, the code for twelve oz cup of chai latte is CAL12 and 16 oz cup of matcha latte is ML16.
  • Notice there are no spaces between the code and quantity.
  • The number of ozs can be any amount greater than or equal to zero.
  • Ask the user for the following inputs (and no other input) in this order, as shown in the example output below:
  • A single order code like: CA123 (no spaces allowed!!)
  • A 'y' or 'n' (without the quotes) for the repeat loop
  • Store the order code in a single String variable.
  • Then use substring() to analyze and process the input String to print a full description of the order.
  • Note that you are not allowed to use any String methods other than substring, charAt, and length in this program
  • Add a do-while statement that allows the user to repeat the program by entering a 'y' (without the quotes)
  • If the user enters an invalid code, display the message, "Sorry! We don't serve that drink." as shown in the example output.
  • Submit Cafe.java to Canvas when you are finished.

The output of your program should look identical to the sample output below except user input may vary.:

Welcome to the Java Jive Bakery and Cafe!

Enter the drink order code: DC12
12 oz drip coffee coming right up!

Another item? (y/n) y

Enter the drink order code: TEA30
30 oz tea coming right up!

Another item? (y/n) Y

Enter the drink order code: SES5
5 oz single espresso coming right up!

Another item? (y/n) y

Enter the drink order code: ML150
150 oz matcha latte coming right up!

Another item? (y/n) y

Enter the drink order code: ABC6
Sorry! We don't serve that drink.

Another item? (y/n) n

Thank you for your order!



Assignment 16.1: Getting Methodical (10 pts)

  • Copy and paste the starter code into a new file called Methodical.java
  • Write the required methods as described by the comments (i.e. you fill in the body of the method).
  • Then, run the code when you are finished to see if you wrote the methods correctly.
  • Check the test results and make any alterations to your methods as necessary.
  • When all of the tests pass, upload your code to Canvas.


/*
 * @author
 * CIS 36A
 *
 */

public class Methodical {
    /*
     * Given two int values, returns their sum.
     * Unless the two values are the same, then return double their sum.
     * sumDouble(1, 2) → 3
     * sumDouble(3, 2) → 5
     * sumDouble(2, 2) → 8
     */
   
    public static int sumDouble(int a, int b){
        return 0;
    }
   
    /*
     * Given 2 ints, a and b, return true if one of them is 10
     * or if their sum is 10.
     * makes10(9, 10) → true
     * makes10(9, 9) → false
     * makes10(1, 9) → true
     */

    public static boolean makes10(int a, int b) {
        return false;
    }
    /*
     * We have two monkeys, a and b, and the parameters
     * aSmile and bSmile indicate if each is smiling.
     * We are in trouble if they are both smiling
     * or if neither of them is smiling.
     * Return true if we are in trouble.
     * monkeyTrouble(true, true) → true
     * monkeyTrouble(false, false) → true
     * monkeyTrouble(true, false) → false
     */

    public static boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
        return false;
    }
   
    /*Return true if the given non-negative number is a multiple of 3
    * or a multiple of 5. Use the % "modulus" operator
    * or35(3) → true
    * or35(10) → true
    * or35(8) → false
    * */

    public static boolean or35(int a) {
        return false;
    }

    /*
     * Given a string, return a new string where "not " has been added to the front.
     * However, if the string already begins with "not", return the string unchanged.
     * notString("candy") → "not candy"
     * notString("x") → "not x"
     * notString("not bad") → "not bad"
     */
   
    public static String notString(String str) {
        return "";
    }

    /*
     * Given a string, return a new string where the first and last chars have been exchanged
     * frontBack("code") → "eodc"
     * frontBack("a") → "a"
     * frontBack("ab") → "ba"
     */
   
    public static String frontBack(String str) {
        return "";
    }
   
    /*
     * We'll say that a number is "teen" if it is in the range 13..19 inclusive.
     * Given 3 int values, return true if 1 or more of them is/are teen.
     * hasTeen(13, 20, 10) → true
     * hasTeen(20, 19, 10) → true
     * hasTeen(20, 10, 13) → true
     */

    public static boolean hasTeen(int num1, int num2, int num3) {
        return false;
    }
   



    public static void main(String[] args)
    {
        int result;
        boolean answer;
        String value;
        System.out.println("***Testing sumDouble***\n");
        result = sumDouble(1, 2);
        System.out.println("Should print 3: " + result);
        result = sumDouble(3, 2);
        System.out.println("Should print 5: " + result);
        result = sumDouble(2, 2);
        System.out.println("Should print 8: " + result +"\n");
      
        System.out.println("***Testing makes10***\n");
        answer = makes10(9, 10);
        System.out.println("Should be true: " + answer);
        answer = makes10(9, 9);
        System.out.println("Should be false: " + answer);
        answer = makes10(1, 9);
        System.out.println("Should be true: " + answer + "\n");
          
        System.out.println("***Testing monkeyTrouble***\n");
        answer = monkeyTrouble(true, true);
        System.out.println("Should be true: " + answer);
        answer = monkeyTrouble(false, false);
        System.out.println("Should be true: " + answer);
        answer = monkeyTrouble(true, false);
        System.out.println("Should be false: " + answer + "\n");
      
        System.out.println("***Testing or35***\n");
        answer = or35(3);
        System.out.println("Should be true: " + answer);
        answer = or35(10);
        System.out.println("Should be true: " + answer);
        answer = or35(8);
        System.out.println("Should be false: " + answer + "\n");
      
        System.out.println("***Testing notString***\n");
        value = notString("candy");
        System.out.println("Should be not candy: " + value);
        value = notString("x");
        System.out.println("Should be not x: " + value);
        value = notString("not bad");
        System.out.println("Should be not bad: " + value + "\n");
      
        System.out.println("***Testing frontBack***\n");
        value = frontBack("code");
        System.out.println("Should be eodc: " + value);
        value = frontBack("a");
        System.out.println("Should be a: " + value);
        value = frontBack("ab");
        System.out.println("Should be ba: " + value + "\n");
      
      
        System.out.println("***Testing hasTeen***\n");
        answer = hasTeen(13, 20, 10);
        System.out.println("Should be true: " + answer);
        answer = hasTeen(20, 19, 10);
        System.out.println("Should be true: " + answer);
        answer = hasTeen(20, 10, 13) ;
        System.out.println("Should be true: " + answer);
        answer = hasTeen(20, 10, 45) ;
        System.out.println("Should be false: " + answer + "\n");
      
        System.out.println("***End of Tests***");
      
    }
   
}






Assignment 17.2: More Method Practice (10 pts)

  • Open a file named MorePractice.java and copy and paste the below contents into the file
  • Write the required methods as described by the comments (i.e. you fill in the body of the method).
  • Then, run the code when you are finished to see if you wrote the methods correctly.
  • Check the test results and make any alterations to your methods as necessary.
  • When all of the tests pass, upload your code to Canvas.
/*
 * @author
 * CIS 36A
 *
 */import java.util.Scanner;

public class MorePractice {
    /**
     * Given a String, take the last char and return a new String with the last char added at the front and back,
     * so "cat" yields "tcatt". The original String will be length 1 or more.
     * wrapAround("cat") → "tcatt"
     * wrapAround("Hello") → "oHelloo"
     * wrapAround("a") → "aaa"
     * @param str the input String
     * @return a new String with the last char added to front and back
     */
  
    public static String wrapAround(String str) {
        return "";
    }
  
    /**
     * Given 2 strings, a and b, return a String of the form short+long+short,
     * with the shorter String on the outside and the longer String on the inside.
     * The Strings will not be the same length, but they may be empty (length 0).
     * combineString("Hello", "hi") → "hiHellohi"
     * combineString("hi", "Hello") → "hiHellohi"
     * combineString("aaa", "b") → "baaab"
     * @param a the first String to combine
     * @param b the second String to combine
     * @return a new String short+long+short
    */
    public static String combineString(String a, String b)
    {
        return "";
    }
  
    /**
     * Given a String of even length, return a String
     * made of the middle two chars, so the String
     * "string" yields "ri".
     * Note: You can assume the String length will be at least 2.
     * middleChars("string") → "ri"
     * middleChars("code") → "od"
     * middleChars("Practice") → "ct"
     * @param str the String to extract the middle
     * @return the middle of the String
     */
    public static String middleChars(String str){
        return "";
    }

    /**
     * Given a string, return a new String made of 3 copies of the last 2 chars of the original String.
     * The String length will be at least 2.
     * anotherEnd("Hello") → "lololo"
     * anotherEnd("ab") → "ababab"
     * anotherEnd("Hi") → "HiHiHi"
     * @param str the String to copy
     * @return the repeated characters
     */
    public static String anotherEnd(String str) {
        return "";
    }
   
    /**
     * Given a String, determines whether the given character is in the String
     * contains('@', "bob@jobs.com") → true
     * contains('@', "bobajobs.com") → false
     * contains('2', "tr2dat") → true
     * @param c the character to locate in the String
     * @param s the String to search
     * @return whether c is in s
     */
    public static boolean contains(char c, String s) {
        return false;
    }
  

    public static void main(String[] args)
    {
        String value;
        boolean b;
        System.out.println("***Testing wrapAround***\n");
        value = wrapAround("cat");
        System.out.println("Should print tcatt: " + value);
        value = wrapAround("Hello");
        System.out.println("Should print oHelloo: " + value);
        value = wrapAround("a");
        System.out.println("Should print aaa: " + value +"\n");
     
        System.out.println("***Testing combineString***\n");
        value = combineString("Hello", "hi");
        System.out.println("Should be hiHellohi: " + value);
        value = combineString("hi", "Hello");
        System.out.println("Should be hiHellohi: " + value);
        value = combineString("aaa", "b");
        System.out.println("Should be baaab: " + value + "\n");
         
        System.out.println("***Testing middleChars***\n");
        value = middleChars("string");
        System.out.println("Should be ri: " + value);
        value = middleChars("code");
        System.out.println("Should be od: " + value);
        value = middleChars("Practice");
        System.out.println("Should be ct: " + value + "\n");
     
        System.out.println("***Testing anotherEnd***\n");
        value = anotherEnd("Hello");
        System.out.println("Should be lololo: " + value);
        value = anotherEnd("ab");
        System.out.println("Should be ababab: " + value);
        value = anotherEnd("feet");
        System.out.println("Should be etetet: " + value + "\n");
       
        System.out.println("***Testing contains***\n");
        b = contains('@', "bob@jobs.com");
        System.out.println("Should be true: " + b);
        b = contains('@', "bobajobs.com");
        System.out.println("Should be false: " + b);
        b = contains('2', "tr2dat");
        System.out.println("Should be true: " + b);
     
        System.out.println("***End of Tests***");

      
    }
  

}


Assignment 15.1: More Sentences (10 pts)
  • Write a program that allows a user to enter a sentence and then the position of two characters in the sentence.
  • The program should then report whether the two characters are identical or different.
  • When the two characters are identical, the program should display the message:
<char> and <char> are identical!
  • Note that <char> should be replaced with the characters from the String. See example output below for more information.
  • When the two characters are different, the program should display the message:
<char> and <char> are unique characters.
  • Note that <char> should be replaced with the characters from the String. See example output below for more information.
  • Name your program Sentences.java
  • Your program must use a do-while loop to allow the user to enter a series of sentences, or "X" to exit.
    • The program should accept both lower and upper case "X" as an indication the user wishes to exit the program.
    • Please see example output below
  • It should also verify that the user provides numerical input for the positions of the characters in the String.
    • Hint: Use a while loop and !input.nextInt() to check for input mismatch exception.
    • See Lesson 14 notes for a discussion on input mismatch exception
    • You will need two while loops, one for each input.nextInt() statement for the numeric location of each character in the String
  • Important: Note that you will need to use input.nextLine() to account for the fact that the loop causes an input.nextInt() to come before an input.nextLine().
    • See lesson 14 notes regarding the problem that can occur when you use input.nextInt() before an input.nextLine()
  • When your program runs identically to the example output below, submit it to Canvas.

Your output should look identical to the following, except user input will vary:

Welcome!
This program compares two letters in a sentence.

Enter a sentence or X to exit: Let's have cake and ice cream for dinner!
Enter the numeric location of the first letter: 1
Enter the numeric location of the second letter: 9

e and e are identical.

Enter a sentence or X to exit: "Flight Behavior" is a good book.
Enter the numeric location of the first letter: six

Error! Enter a number, not text!
Enter the numeric location of the first character: six

Error! Enter a number, not text!
Enter the numeric location of the first character: six

Error! Enter a number, not text!
Enter the numeric location of the first character: 6
Enter the numeric location of the second letter: 10

t and h are unique characters.

Enter a sentence or X to exit: Summer vacation is almost here!
Enter the numeric location of the first letter: 2
Enter the numeric location of the second letter: three

Error! Enter a number, not text!
Enter the numeric location of the second character: three

Error! Enter a number, not text!
Enter the numeric location of the second character: three

Error! Enter a number, not text!
Enter the numeric location of the second character: 3

m and m are identical.

Enter a sentence or X to exit: x
Goodbye!

Assignment 15.2: Comparing Characters (10 pts)

  • Write a program that tests if the first or last letter of a word is earlier in the alphabet.
  • If the characters are the same, we will note that as well.
  • Recall that we may compare String characters to each other because they are stored as numbers in the computer, according to a standard known as Unicode.
  • Name the project FirstLast with a class called FirstLast.java and include all your code in this single file.
  • Ask the user for the following inputs (and no other input) in this order and each on their own line:
    1. a word such as "easy" (without the quote marks) as a String
    2. "y" or "n" (without the quote marks) to see if the program should loop again
    • Assume the user enters only valid data.
    • See sample output below
  • Use the substring method that we learned in Lesson 14 to extract the first and last characters, and then test if the first or last letter of the word is earlier in the alphabet.
    • Do NOT use charAt() or you will not receive credit for this assignment. You must use substring() to access the first and last characters.
  • Note the use of "" around the letter in the output below. These must be included.
  • If the letters are the same then print, "Letters are the same." (without the quotes) as shown in the sample output.
  • Add a while statement that allows the user to repeat the program by inputting a "y" (without the quotes), and exiting the loop for any other character entered, as shown in the sample output.
  • When your program works identically to the example output below, submit it to Canvas:

Your output should look identical to the output below:

***Comparing First and Last Characters***

Input a word: easy
First letter "e" is earlier in the alphabet.

Run again? (y/n) y

Input a word: zebra
Last letter "a" is earlier in the alphabet.

Run again? (y/n) y

Input a word: Zebra
First letter "Z" is earlier in the alphabet.

Run again? (y/n) y

Input a word: eve
Letters are the same.

Run again? (y/n) n


Assignment 15.3: Being Methodical (10 pts)


  • Open Eclipse and create a new project called Methodic with a Java class called Methodic.java
  • Copy and paste the below starter code into your file:
/*
* @author
* CIS 36A
*
*/
public class Methodic {
public static void main(String[] args)
{
System.out.println("***Testing areaRectangle***\n");
System.out.printf("Should print 15.0: %.1f\n", areaRectangle(5.0, 3.0));
System.out.printf("Should print 5.3: %.1f\n", areaRectangle(3.5, 1.5));
System.out.println();

System.out.println("***Testing areaTriangle***\n");
System.out.printf("Should print 7.5: %.1f\n", areaTriangle(5.0, 3.0));
System.out.printf("Should print 2.6: %.1f\n", areaTriangle(3.5, 1.5));
System.out.println();

System.out.println("***Testing minNum***\n");
System.out.println("Should print 2: " + minNum(9, 2));
System.out.println("Should print 9: " + minNum(9, 9));
System.out.println("Should print 2: " + minNum(2, 9));
System.out.println();

System.out.println("***Testing firstLetter***\n");
System.out.println("Should print A: " + firstLetter("Abracadabra"));
System.out.println("Should print z: " + firstLetter("zebra"));
System.out.println("Should print h: " + firstLetter("hello there!"));
System.out.println();

System.out.println("***End of Tests***");

}
}

  • Then, either above or below main (not in the {} for main), but inside the { } of the class Methodic, write the following methods:
  • Name: areaRectangle
    • Takes in 2 double parameters - one for the length and one for the width
    • returns the area of the rectangle as a double
  • Name: areaTriangle
    • Takes in 2 double parameters - one for the base one for the height
    • returns the area of the triangle as a double
  • Name: minNum
    • takes in two integer parameters
    • returns the smaller of the two numbers as an integer
  • Name: firstLetter
    • takes in one String parameter
    • returns the first character in the String
  • After writing your methods, compile and run your code.
  • Adjust any methods that do not give the correct output in the tests
  • When all of your tests pass, submit your program to Canvas.

Important: To receive credit, you must only use concepts and methods taught in class to complete these assignments

Assignment 12.2: Tallying Votes (10 pts)

  • Elections are a formal group-decision making process by which a population chooses a person to hold office, such as the mayor of a city.
  • Another use of elections is to accept or reject a political proposition. 
  • Most election results are tallied, or counted, using electronic voting.
  • Most electronic voting machines use a computer to take care of the chore of casting and counting votes.
  • Elections are on our minds as we prepare for the 2020 presidential race.
  • In this assignment we will develop a program to count votes.
  • The user enters votes based on a simple menu that presents the candidates.
  • The user then inputs a single character (upper or lowercase A-C) to choose their candidate from the menu.
  • Entering an 'X' (without the quotes) will exit the tallying operation and present a summary of the votes.
  • Name the source code file Vote.java.
  • Present a list of candidates to the user and allow her to enter a single character as input, and no other input, as shown in the Example Output.
  • Feel free to chose any candidate names you like for the voters to select. You do not have to use the 3 candidates from my example output.
  • Use an indefinite while loop to allow multiple votes to be cast on your voting machine.
  • After all the votes are entered and the user enters an 'X', exit the loop and report the vote count by candidate names and neatly aligned as shown in the Example Run.
  • Your program should also report an error message if the user enters a letter other than A-C or X, as shown below.
  • Please use proper style as demonstrated in class
  • When your program works identically to the example output below, submit it to Canvas.

Example Output:

***Voting Machine!***

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: C
You chose candidate The Black Panther

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: c
You chose candidate The Black Panther

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: Z
Invalid input. Please enter A-C or X

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: A
You chose candidate Dalai Lama

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: B
You chose candidate Bernie Sanders

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: a
You chose candidate Dalai Lama

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: B
You chose candidate Bernie Sanders

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: C
You chose candidate The Black Panther

Candidate A: Dalai Lama
Candidate B: Bernie Sanders
Candidate C: The Black Panther

Enter your choice (A-C) or X to exit: X

***Election Results!***
Dalai Lama: 2
Bernie Sanders: 2
The Black Panther: 3


Assignment 21.1: Checking on the Drought
  • The California drought is a topic that has been weighing heavily on the minds of many people in this state.
  • With all the rain we have gotten this year, we are all hoping the drought is over
  • Let's examine some rainfall data for Silicon Valley to get a sense of how this year's rainfall compares to the average rainfall.
  • For this assignment, you will be practicing arrays and File I/O.
  • First, create a new file called average_rain.txt.
  • Then, copy and paste the following data into your file. Make sure that each value is on its own line and that there are no blank lines between values.
2.99
3.31
2.05
1.06
0.39
0.08
0.08
0.08
0.24
0.79
1.89
2.13

  • This data represents the average monthly rainfall for San Jose as measured between 1961-1990.
  •  Note that each data point is the total rainfall for one of the 12 months of the year. The first data point represents the average rainfall in January and the last data point represents the average rainfall in December.
  • Save your file and then create a new text file called rain2018_19.txt.
  • Copy and paste the following data into this file. Again make sure that each data point is on its own line and that there are no blank lines between data points.
2.89
5.61
3.20
0.00
0.00
0.00
0.00
0.00
0.00
0.00
1.92
1.53

  • This data represents the rainfall in San Jose from March 2018-February 2019, with the first number representing the rainfall in January 2018 and the last number representing the rainfall in December 2018
  • Note that each data point is the average rainfall for one of the 12 months of the year.
  • The first data point represents the average rainfall in January, and the last data point represents the average rainfall in December.
  • Now, open Eclipse and create a new Java source file named Rainfall.java.
  • The first goal of our program is to read the input data from our two files and store the data in two separate arrays - one array for the 2018-19 rainfall data and one array for the average rainfall data.
  • What size should you make these arrays? Hint: How many months are there in the year?
  • After you have declared your arrays, you need to open each file and, using a loop, write the data into the slots of your array.
  • What kind of loop do you need here? Hint: Do you know in advance how many data points are in each file? Try a for loop.
  • You will need to open two different files and write the contents into two different arrays.
  • Therefore, you will need to close the stream for one file before you open the other file, like so:
input.close();
input = new Scanner(averageFile);
  • Your program should write the results to a file in the form of a table that looks like this:


Rainfall in San Jose: A Comparison

Average     2018-9     Deficit
2.99        2.89       0.10
3.31        5.61       -2.30
2.05        3.2        -1.15
1.06        0.0        1.06
0.39        0.0        0.39
0.08        0.0        0.08
0.08        0.0        0.08
0.08        0.0        0.08
0.24        0.0        0.24
0.79        0.0        0.79
1.89        1.92       -0.03
2.13        1.53       0.60

Total deficit: -0.06


  • To do so, you will need another loop to write the contents of your arrays to the file. Create another textfile called rain_comparison.txt and write the above data to the file.
  • Note that you will need to adjust the number of tabs until your data is lined up properly as in the image above.
  • Note that you should also print the total deficit below the table, as shown above. Hint: keep a running sum of the deficit inside your final for loop
  • When your program creates an output file whose contents are identical to the output above, then submit your Rainfall.java program to Canvas.


Assignment 21.2: Customer Data (10 pts)
  • Write a program that reads in a series of names, along with their gender, from a file.
  • The file is called names.txt.
  • The program uses a loop to read in each name from the file and store each person's title (Mr. or Ms. or Mx.) + name in an array called customers.
  • Note: you can assume that the size of the array is know ahead of time to be 15.
  • The program should then call two methods.
  • The first method:
    • The method is named capitalizeArray
    • It take in a String array
    • It alters the values in the String array to capitalize all of the letters
    • This method must use a for loop. It cannot call any outside methods that we have not discussed in this class.
    • It returns nothing.
  • The second method:
    • The method is named print
    • It takes in an array of Strings
    • It opens up a new PrintWriter and connects it to a file called customers.txt
    • It prints out the array to the file using a for loop
    • It closes the PrintWriter
    • It returns nothing
  • Once you have filled the customers array with titles and names, call the capitalizeArray method to capitalize all the names in the array.
  • Next, call the print method to display each of the capitalized names in the customers.txt file
  • Copy and paste the starter code below into a new file called Customers.java
/**
 * @author
 *
 */
import java.util.Scanner;
public class Customers
{
    /**
     * Write the javadoc comment for capitalizeArray here
     */
    public static void capitalizeArray(String[] customers)
    {
        return;
    }
    
    /**
     * Write the javadoc comment for printArray here
     */
    public static void printArray(String[] customers) throws IOException
    {
        return;
    }
    
    public static void main(String[] args)
    {
        //declare your customers array here
      
        String name, gender;
        
        
        //Use a while loop to read in the data from the file
        
        
        //call your two methods
    }
}

  • Copy and paste the below data into a file called names.txt:
Barbara Stanton
F
Timoteo Martinez
M
Ally Gu
O
Xing Xiao
M
Dung Kim
F
Tanya White
F
Alan Ngo
M
Abir Fadel
M
Nataly Luna
F
Charles Atkinson
M
Stacey Cahill
O
Stephanie Teatro
F
Ping Li
M
June Park
F
Binh Nguyen
M
  • Below is the output that your program should give in a file called customers.txt:
MS. BARBARA STANTON
MR. TIMOTEO MARTINEZ
MX. ALLY GU
MR. XING XIAO
MS. DUNG KIM
MS. TANYA WHITE
MR. ALAN NGO
MR. ABIR FADEL
MS. NATALY LUNA
MR. CHARLES ATKINSON
MX. STACEY CAHILL
MS. STEPHANIE TEATRO
MR. PING LI
MS. JUNE PARK
    MR. BINH NGUYEN




Assignment 18.1: Billboard Top Songs (10 pts)

  • In this assignment we will write a program that stores 10 Strings in a String array -- representing the Billboard top 10 songs of November, 2019 -- and 10 doubles in a double array (duration of the song) and then writes the contents of the two arrays to the console.
  • Create a new Java file, and save it as Billboard.java.
  • At the top of main declare a String array named titles of length 10. 
  • Then, declare a double array of length 10 named durations.
  • Store the following values in the String array, one at each index:
"Someone You Loved"
"Circles"
"Senorita"
"Good as Hell"
"Memories"
"Truth Hurts"
"No Guidance"
"Lose You to Love Me"
"Panini"
"10,000 Hours"
  • Remember: you can do this, using either static or non-static intialization.
  • Next, store the following song durations in the double array, one at each index:

1.54
3.26
3.14
3.43
3.20
2.42
2.38
3.16
3.45
3.28

  • Now, inside of main, add the following print statement:

    System.out.println("Billboard Top 10 Tracks:");

  • Next, write a method that prints out the the two arrays.
  • Copy and paste the below javadoc comment and method signature outside of main:
/**
* Prints out the values of two arrays side-by-side
* @param array1 the first array to print
* @param array2 the second array to print
*/
public static void printArrays(String array1[], double array2[]){
    //fill in method body here!
}

  • Inside your method, you will need a for loop to print the arrays to the console, side-by-side, as shown below, with the duration in parenthesis, displayed to two decimal places:
Someone You Loved (1.54)
Circles (3.26)
Senorita (3.14)
Good as Hell (3.43)
Memories (3.20)
Truth Hurts (2.42)
No Guidance (2.38)
Lose You to Love Me (3.16)
Panini (3.45)
10,000 Hours (3.28)
  • See the class notes if you get stuck for an example of using for loops with arrays or how to write a method to display an array to the console.
  • Next, below your System.out.print statement for the Billboard Top 10 Tracks, call the printArrays method, passing it the two arrays as arguments.
  • Finally, compile and run your code and verify that the following output appears in the console window:

    Billboard Top 10 Tracks
    Someone You Loved (1.54)
    Circles (3.26)
    Senorita (3.14)
    Good as Hell (3.43)
    Memories (3.20)
    Truth Hurts (2.42)
    No Guidance (2.38)
    Lose You to Love Me (3.16)
    Panini (3.45)
    10,000 Hours (3.28)
  • Submit your Billboard.java program to Canvas when you are finished.

Activity 20.3: NASA Temperature Data (10 pts)

  • In this activity we will work with a real data set from climate.NASA.gov
  • One of NASA's important roles is to track Climate Change.
  • NASA records data related to average yearly temperatures, monthly atmospheric carbon dioxide levels, changes in sea ice, and sea levels.
  • The purpose of this program will be to search the data set for the years with smallest and largest average temperatures, and to write these years into a file.
  • Find a partner for pair programming
  • Create a new project folder called Climate with a new Java file named Climate.java.
  • Copy and paste the below starter code into Climate.java:

/**
 * @author
 * @author
 * CIS 36A
 * Activity 20.3
 */

//add import statement(s) here
import java.util.Scanner;

public class Climate {
    public static void main(String[] args) { //throw exception here
       
int min_index, max_index;
        final int ARRAY_LENGTH = 139;
    
        //declare arrays here
       
        //declare File variables here
        //declare Scanner variable here
        //declare PrintWriter variable here
       
        //write for loop here to read in data from file to two arrays
       
        //call the two methods:
        //min_index = //call findMin
        //max_index = //call findMax
       
        //replace below statements to write to file instead of console
        System.out.println("The hottest year since 1880 is " + years[max_index]);
        System.out.println("The coldest year since 1880 is " + years[min_index]);
       
        //don't forget to close Scanner and PrintWriter!
    }
}
  • Next we need two text files
  • Right-click the Climate project folder and select New->File. Name your file globalTemperatures.txt
  • Make sure that you did not accidentally save your file under the src folder. If you did, you can simply drag and drop it into the main Climate project folder.
  • Then, create a second (empty) text file called output.txt using the same approach.
  • Copy and paste the below data into globalTemperatures.txt:
1880    -0.19
1881    -0.10
1882    -0.11
1883    -0.19
1884    -0.28
1885    -0.31
1886    -0.32
1887    -0.35
1888    -0.18
1889    -0.11
1890    -0.37
1891    -0.23
1892    -0.26
1893    -0.31
1894    -0.31
1895    -0.22
1896    -0.11
1897    -0.12
1898    -0.27
1899    -0.18
1900    -0.09
1901    -0.15
1902    -0.28
1903    -0.38
1904    -0.48
1905    -0.28
1906    -0.22
1907    -0.39
1908    -0.43
1909    -0.47
1910    -0.42
1911    -0.43
1912    -0.35
1913    -0.35
1914    -0.15
1915    -0.12
1916    -0.33
1917    -0.44
1918    -0.28
1919    -0.26
1920    -0.26
1921    -0.18
1922    -0.28
1923    -0.25
1924    -0.26
1925    -0.21
1926    -0.09
1927    -0.20
1928    -0.19
1929    -0.34
1930    -0.14
1931    -0.09
1932    -0.16
1933    -0.28
1934    -0.14
1935    -0.20
1936    -0.16
1937    -0.04
1938    -0.03
1939    -0.03
1940    0.12
1941    0.18
1942    0.05
1943    0.07
1944    0.21
1945    0.09
1946    -0.07
1947    -0.04
1948    -0.10
1949    -0.11
1950    -0.18
1951    -0.07
1952    0.01
1953    0.07
1954    -0.14
1955    -0.14
1956    -0.20
1957    0.04
1958    0.07
1959    0.03
1960    -0.02
1961    0.06
1962    0.04
1963    0.07
1964    -0.20
1965    -0.10
1966    -0.05
1967    -0.02
1968    -0.07
1969    0.07
1970    0.03
1971    -0.09
1972    0.01
1973    0.16
1974    -0.08
1975    -0.02
1976    -0.11
1977    0.17
1978    0.06
1979    0.16
1980    0.27
1981    0.33
1982    0.13
1983    0.31
1984    0.16
1985    0.12
1986    0.18
1987    0.33
1988    0.41
1989    0.28
1990    0.44
1991    0.41
1992    0.22
1993    0.24
1994    0.31
1995    0.44
1996    0.33
1997    0.47
1998    0.62
1999    0.39
2000    0.40
2001    0.53
2002    0.62
2003    0.60
2004    0.53
2005    0.67
2006    0.62
2007    0.64
2008    0.51
2009    0.63
2010    0.70
2011    0.57
2012    0.62
2013    0.65
2014    0.73
2015    0.87
2016    0.99
2017    0.90
2018    0.82

  • Note that the first column above represents the year, and the second column represents the change in global surface temperature relative to 1951-1980 average temperatures (without smoothing)
  • You can find this data set online here.
  • Next, create two arrays of length 139 - one a String array named years, and one a double array named temperatures.
    • NASA has tracked yearly temperatures changes for 139 years
  • Using a for loop, read in the above data into the two arrays.
  • Note that you should use only one for loop.
    • Inside this for loop, alternate reading the data into each array, starting with the String array for the year.
    • Recall that for the String array, you will use input.next() and for the integer array, you will use input.nextInt().
  • For an example of reading data into an array using a for loop, please see the Lesson 19 notes, the example entitled: Example Program Using Arrays to Collect and Display Data Items
  • Next, add two methods to your program:
/**
* Searches an array for the location of the minimum value
* @param array, an array of doubles
* @return the index where the minimum value is located
*/
public static int findMin(double[] array) {
    double min = Double.MAX_VALUE; //largest possible double stored as a variable
           int min_index = -1;
    //fill in the rest of the method body here
    return min_index;
}


/**
* Searches an array for the location of the maximum value
* @param array, an array of doubles
* @return the index where the maximum value is located
*/
public static int findMax(double[] array) {
    double max = Double.MIN_VALUE; //smallest possible double stored as a variable
    int max_index = -1;
 //fill in the rest of the method body here
return max_index;
}
  • Implement the method bodies according to the description in the Javadoc comment and also using the method information below:
findMin Method:
  • This method takes an array of doubles as a parameter
  • It initializes a variable named min to be a large number (largest possible double)
  • It initializes a second variable min_index to be -1
  • Then, uses a for loop to step through the array
  • At each index in the array, it compares the double stored at that index to the min
  • If the double stored at index i is smaller than min, it assigns min to be array[i]
  • It will also assign min_index to be i
  • It returns min_index
findMax Method:
  • This method takes an array of doubles as a parameter
  • It initializes a variable named max to be a small number (smallest possible double)
  • It initializes a second variable max_index to be -1
  • Then, uses a for loop to step through the array
  • At each index in the array, it compares the double stored at that index to the max
  • If the double stored at index i is bigger than max, it assigns max to be array[i]
  • It will also assign max_index to be i
  • It returns max_index
  • Note that these methods implement the second algorithm that you wrote for Assignment 2.1: Two Algorithms, at the beginning of the quarter.
  • Now, inside of main, call the two methods to find the years with the highest and lowest average temperatures.
  • Once you have that information, write it into output.txt.
  • Your output.txt should contain the following output when you are finished:
The hottest year since 1880 is 2016
The coldest year since 1880 is 1904

  • When your program is giving the correct output, upload Climate.java to Canvas.

You will be given a program similar to the one below on your final. If you understand how to write the program below, you should have no trouble writing the one on the final exam. You will not be asked to write a homework assignment on the exam.

Customer Data: Area Codes

  • You work for a company that tracks customer information, including name, gender and phone numbers
  • Your company has received some text files containing potential customer data, including name, gender and phone number.
  • These text files all have the same format.
    • The first line of the file specifies the number of customers contained inside the file
    • And the subsequent lines of the file contain the customer information.
  • You can assume for all customers in the files, exactly half will have a phone number with an 831 area code.
  • And, exactly half have a phone numbers have a 408 area code.
  • Write a program that reads in all of the customer information using a loop, and stores the names of the customers in two different string arrays - each array of length totalCustomers / 2.
  • One array should store the customers with a 408 area code and one array should store the customers with an 831 area code.
  • When the customers are stored in each array, they should be stored as Mr., Ms. or Mx. depending on the gender below their name in the file.
    • In other words, whenever the customers.txt file contains an M below the customer name, you should place the word Mr. before the name.
    • Whenever the customers.txt file contains an F below the customer name, you should place the word Ms. before the name.
    • Finally, whenever the file contains an O below the customer name, you should place the word Mx. before the name.
  • Each customer should also be stored along with their phone number, in the format:
title name: phone number
  • You should also format the phone numbers by calling the validatePhone method defined below.
  • Finally, you will be required to write the two arrays to a file.
  • Each array should be written to a different file.
  • The 408 area code array should be written to a file called SantaClaraCounty.txt
  • The 831 area code array should be written to a file called MontereyCounty.txt
  • You must write the arrays to the file by calling the printArray method.
  • Note that you will need to call printArray twice - once for each array.
  • Important: Your solution must only use concepts and methods covered in this class to receive credit.
Method requirements
  • validatePhone Method:
    • The method is named validatePhone

    • It takes a String parameter for the phone number

    • If the number is the correct length, it will convert the String into a phone number in the format (XXX) XXX-XXXX

    • However, if the phone number is an incorrect length, the phone number will not be formatted as above.

    • Instead, the method should will append the String "(invalid)" to the end of the phone number
    • Note that to receive credit, you can only call String methods we have covered in this class.
    • The method returns a String for the updated phone number.

  • printArray Method:
    • The method is named printArray
    • It throws IOException
    • It takes in two parameters:
      •  the first parameter is an array of Strings,
      • the second parameter is a String for the name of a text file in which to write out the data
    • The method must open the file whose name is passed in as a parameter
    • It declares a PrintWriter and uses it to write to the specified file
    • It uses a for loop to print out the contents of the array in the file, with each element on its own line
    • It then closes the PrintWriter.
    • It returns nothing.
  • On the final, you will be required to write a the complete method, including its signature, and a Javadoc comment for each method
  • The method signature is provided below but will not be provided on the final.

  • Copy and paste the starter code below into a new class called AreaCodes.java

/*
 * @author
 * CIS 36A
 */
import java.io.*;
import java.util.Scanner;

public class AreaCodes {
    
    public static void main(String[] args) //update to throw exception
    {
        String name, gender, phone;
        final String FILE_NAME;
        final int ARRAY_SIZE;
     
        //prompt user for file name      
        //Declare File and Scanner for reading from the file
        //Note: No PrintWriter should be used in main
        //declare your two arrays

        //Use below variables to keep track of array index inside while loop
        int i = 0;
        int j = 0;
        while(??????)
        {
            //read in name and gender
            
            //if statements related to gender
            
            //read in phone
            
            //if statements for phone
            
        }
   
        
      
        
    }
   
          //write Javadoc comment here
    public static String validatePhone(String phone)
    {
        return "";
    }
   
          //write Javadoc comment here
    public static void printArray(String[] names, String fileName)//update to throw Exception
    {
        //PrintWriter needed in this method, not in main
        return;
    }
}

Sample Output:

Welcome!
Please enter the name of an input file: customers22.txt

Thank you!
Please check SantaClaraCounty.txt and SantaCruzCounty.txt for the customer data.


Sample Output:


Welcome!
Please enter the name of an input file: infile1234.txt

Thank you!
Please check SantaClaraCounty.txt and SantaCruzCounty.txt for the customer data.

Example input file:

12
Jiming Wu
F
4082123458
James Brown
M
8315678432
Leanna Perez
F
4087654433
Shakil Smith
M
4082123333
Jung Ahrin
F
831925778
Pedro Martinez
M
408616232323
Ally Gu
O
4089256776
Tamara White
F
8317778978
Alvin Ngo
M
4089256677
Abir Fadel
M
8316645325
Brad Feinman
M
8312023443333
Xiaohang Yue
M
8318990033

Corresponding Output Files:

  •  SantaClaraCounty.txt file:
Ms. Jiming Wu: (408) 212-3458
Ms. Leanna Perez: (408) 765-4433
Mr. Shakhil Smith: (408) 212-3333
Mr. Pedro Martinez: 408616232323 (invalid)
Mx. Ally Gu: (408) 925-6776
Mr. Alvin Ngo: (408)925-6677

  • SantaCruzCounty.txt file:
Mr. James Brown: (831) 567-8432
Ms. Jung Ahrin: 831925778 (invalid)
Ms. Tamara White: (831) 777-8978
Mr. Abir Fadel: (831) 664-5325
Mr. Brad Feinman: 8312023443333 (invalid)
Mr. Xiaohang Yue: (831) 899-0033

Example input file:

4
Xing Li
M
8313214555
Mohammed Abbas
M
4083134444
Kumari Chakrabarti
F
40866677
Stacey Cahill
O
8312123333


Corresponding Output Files:

  • SantaClaraCounty.txt file:
Mr. Mohammed Abbas: (408) 313-4444
Ms. Kumari Chakrabarti: 40866677 (invalid)

  • SantaCruzCounty.txt file:
Mr. Xing Li: (831) 321-4555
Mx. Stacey Cahill: (831) 212-3333


Assignment 18.1: Fun with Fruit (10 pts)
  • In Eclipse, create a Java file named Fruit.java
  • Then, create two text files to be used in the program: fruits.txt, numbers.txt, as described below:
  • Right-click the Fruit project folder and select New->File. Name your file numbers.txt.
  • Important: Make sure your file did not get saved in the src folder. If it did, simply drag and drop the file into the Fruit project folder.
  • Here are the values to place in the numbers.txt file:
10
20
25
30
35
  • Next, create a second file called fruits.txt.
  • Copy the following data into the that file:
apples
cherries
oranges
peaches
strawberries
  • Add the following import statement to the top of your program
    import java.io.*;
    
  • Alter the signature of main() as required for File I/O (see lesson notes if you are unsure).
  • Then, declare a new file object for the numbers.txt input file, and a new Scanner to read in from this file
  • Next, declare a second file object for the fruits.txt input file, and a new Scanner to read from this file
  • Below your code for the file I/O, declare two arrays of size 5 as follows:
    • one array contains Strings and is named fruits
    • one array contains ints and is named number_fruits
  • Assign the data in fruits.txt to the fruits array by reading the data from the file, and assigning each data point to one index in the array.
  • Hint: you can use 5 input.next() statements, or use a for loop (better approach). For example:
fruits[0] = input.next();
  • Also, assign values to the number_animals array by reading in those values from the nums.txt file. For example:
    number_fruits[0] = input.nextInt();
    
  • Now it is time to write the information to the console. Print a header as follows:
    System.out.println("Fun with Fruit:");
    
  • Then, write a for loop to write the contents of the two arrays to the console
  • When you are finished, your output should be identical to the following:
Fun with Fruit:
10 apples
20 cherries
25 oranges
30 peaches
35 strawberries
  • Once it is giving the correct output, submit Fruit.java to Canvas.


Assignment 18.2: How Many Numbers? (10 pts)

  • Open a new Java file named Numerical.java
  • Inside the same project folder as your Java file, create a new text file called input1.txt and a second file named input2.txt
  • Copy and paste the below values into input1.txt:
4
3.2
6.7
2.9
4.6
  • Next, copy and paste the below values into input2.txt:
8
2.1
-5.6
9.0
8.7
-2.2
8.2
9.5
1.4
  • The above input files contain information about arrays.
  • The first line of the file states the size of the array
  • The subsequent lines of the file specify the contents of the array.
  • Write a program that reads in the data from the file, uses the information to create an array of doubles, and then computes the sum and product of the values stored in the array.
    • Note that your program should work with any input file that is structured in the same format at the above two input files.
    • Therefore, you cannot assume that I will run your code with just the two examples.
    • What you can assume is that all input files will have a first line containing the length of the array, followed by a sequence of values to insert into the array.
  • First, you will need to prompt the user to enter the name of a file.
    • Save this file name as a String, and use it to create a new File object.
  • Next, read in the first line of the file to determine how big to make your array.
    • declare an array of the specified length - hint: you must use an integer variable to store the length
  • Note that you will need to use for loops to complete the rest of this assignment.
    • Use the length of the array in the test condition of the for loop
    • Inside the body of the for loop, read in each subsequent number and store it into the array. See class notes and Activity 18.1 for some examples.
    • Using another for loop, sum the numbers and report their sum to the user.
    • Also, multiply the numbers together and report their product to the user.
  • For full credit, I should see two for loops in your code (see above).
  • Also note: The sum and the product should be printed to one decimal value only.
  • Your program should work identically to the sample output below:

Enter the name of the file: input1.txt
Array length = 4

Number 1: 3.2
Number 2: 6.7
Number 3: 2.9
Number 4: 4.6

The sum of the numbers is: 17.4
And the product is: 286.0


  • Another run of the program might give the following output:

Enter the name of the file: input2.txt
Array length = 8

Number 1: 2.1
Number 2: -5.6
Number 3: 9.0
Number 4: 8.7
Number 5: -2.2
Number 6: 8.2
Number 7: 9.5
Number 8: 1.4

The sum of the numbers is: 31.1
And the product is: 220931.3