13 Lesson 14 - Activity 1 - Weeblykeithleyslhs.weebly.com/uploads/6/9/5/2/69521249/lessons... ·...

39
APCS Unit 2 Activity Guide Version 1.0 © Edhesive 13 Lesson 14 - Activity 1 /* * Term 1: Lesson 14 Coding Activity 1 * Test if an integer is not between 5 and 76 inclusive. * * Sample Run 1 * Enter a number: * 7 * False * * * Sample Run 2 * Enter a number: * 1 * True * */ import java.util.Scanner; class Lesson_14_Activity_One { public static void main(String[] args) { //Declare a scanner and input an int. Scanner scan = new Scanner(System.in); System.out.println("Please enter an integer:"); int n = scan.nextInt(); //If n is not in the range, print True. if ( !( n >= 5 && n <= 76)) System.out.println("True"); //Otherwise, print False. else System.out.println("False"); } }

Transcript of 13 Lesson 14 - Activity 1 - Weeblykeithleyslhs.weebly.com/uploads/6/9/5/2/69521249/lessons... ·...

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    13

    Lesson 14 - Activity 1

    /* * Term 1: Lesson 14 Coding Activity 1 * Test if an integer is not between 5 and 76 inclusive. * * Sample Run 1 * Enter a number: * 7 * False * * * Sample Run 2 * Enter a number: * 1 * True * */ import java.util.Scanner; class Lesson_14_Activity_One { public static void main(String[] args) { //Declare a scanner and input an int. Scanner scan = new Scanner(System.in); System.out.println("Please enter an integer:"); int n = scan.nextInt(); //If n is not in the range, print True. if ( !( n >= 5 && n

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    14

    Lesson 14 - Activity 2

    /* * Term 1: Lesson 14 Coding Activity 2 * Write a program to input two integers and print * "Both are positive or zero." to the screen, if both are positive or zero. * Print "One or both are negative." otherwise. */ import java.util.Scanner; class Lesson_14_Activity_Two { public static void main(String[] args) { //Declare a Scanner and input two integers. Scanner scan = new Scanner(System.in); System.out.println("Please enter two integers:"); int x = scan.nextInt(); int y = scan.nextInt(); //Use if-else to produce the necessary output. if(x >= 0 && y >= 0) System.out.println("Both are positive or zero."); else System.out.println("One or both are negative."); } }

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    15

    Lesson 14 - Activity 3

    /* * Term 1: Lesson 14 Coding Activity 3 * The Internet runs on web addresses.The addresses we type represent the IP * address * for each site and how the computer finds an individual web page. * * IP addresses are made up of four numbers, each between 0 and 255 separated * by a period. * For example, 128.253.21.58 is an IP address. * * Write a program to enter four numbers and test if they make up a valid IP * address. * In other words, test to see if the numbers entered are between 0 and 255 * inclusive. * * Sample Run 1 * Please enter the first octet: * 898 * Please enter the second octet: * 34 * Please enter the third octet: * 712 * Please enter the fourth octet: * 45 * Octet 1 is incorrect * Octet 3 is incorrect * * * Sample Run 2 * Please enter the first octet: * 112 * Please enter the second octet: * 200 * Please enter the third octet: * 0 * Please enter the fourth octet: * 254 * IP Address: 112.200.0.254 * */ import java.util.Scanner; class Lesson_14_Activity_Three { public static void main(String[] args) { //Declare a Scanner and input four octets. Scanner scan = new Scanner(System.in);

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    16

    System.out.println("Please enter the first octet: "); int o1 = scan.nextInt(); System.out.println("Please enter the second octet: "); int o2 = scan.nextInt(); System.out.println("Please enter the third octet: "); int o3 = scan.nextInt(); System.out.println("Please enter the fourth octet: "); int o4 = scan.nextInt(); //Set up a flag variable for correct input. int correct = 1; //Check octet 1. if (!(o1 >= 0 && o1 = 0 && o2 = 0 && o3 = 0 && o4

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    17

    Lesson 17 - Activity 1 /* * Term 1: Lesson 17 Coding Activity 1 * Write a program that will input a list of test scores in from the * keyboard. * When the user enters -1, print the average. * * What do you need to be careful about when using -1 to stop a loop? * * Sample Run: * Enter the Scores: * 45 * 100 * -1 * * The average is: 72.5 * * */ import java.util.Scanner; import java.lang.Math; class Lesson_17_Activity_One { public static void main(String[] args) { //Declare a Scanner and prompt for scores. Scanner scan = new Scanner(System.in); System.out.println("Enter the Scores: "); //Input the first score and declare sum and count variables. int test = scan.nextInt(); int sum = 0; int c = 0; //While the input is not -1, increase the count, //add to the sum, and read the next input. while (test != -1) { sum += test; c++; test = scan.nextInt(); } //Calculate and print the average. System.out.println("The average is: " + 1.0*sum/c); } }

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    18

    Lesson 17 - Activity 2

    /* * Term 1: Lesson 17 Coding Activity 2 * Ask the user for two numbers. Print only the even numbers between them, * you should also print the two numbers if they are even. * * Sample Run 1: * * Enter two numbers: * 3 * 11 * * 4 6 8 10 * * Sample Run 2: * * Enter two numbers: * 10 * 44 * * 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 * * */ import java.util.Scanner; import java.lang.Math; class Lesson_17_Activity_Two { public static void main(String[] args) { //Declare a Scanner and input two numbers. System.out.println("Enter two numbers: "); Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); //Create a new variable, start, which is a rounded //up to the nearest even number. int start = a + (a%2); //While start is in range, print it and increase by 2. while (start

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    19

    Lesson 20 - Activity 1

    /* * Term 1: Lesson 20 Coding Activity * * Computer science jobs are in demand. Right now we have a shortage * of people that can do computer programming, and one of the fastest * growing areas of new jobs in the sector are so-called hybrid jobs. * This means you specialize in an area like biology, * and then use computer programming to do your job. * * These hybrid jobs exist in the arts, sciences, * economics, healthcare, and entertainment fields. * * One of these jobs is computational biology. Computational Biology, * sometimes referred to as bioinformatics, is the science of * using biological data to develop algorithms and relations * among various biological systems. * * In this lab we are going to investigate the data from a * grey seal named Gracie. We’ll input the longitude and * latitude data from a tracking device. We want to investigate * the farthest north, south, east and west Gracie has been. * * We will use the latitude to measure this. * Write a program to enter Gracie’s longitude and Latitude data. * Each time through the loop it should ask if you want to continue. * Enter 1 to repeat, 0 to stop. * * Any value for latitude not between -90 and 90 inclusive should be ignored. * * Any value for longitude not between -180 and 180 inclusive should be * ignored. * * * Sample Run: * * Please enter the latitude: * 41.678 * Please enter the longitude: * 69.938 * Would you like to enter another location? * 1 * Please enter the latitude: * 41.755 * Please enter the longitude: * 69.862 * Would you like to enter another location? * 1 * Please enter the latitude: * 41.829 * Please enter the longitude: * 69.947

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    20

    * Would you like to enter another location? * 1 * Please enter the latitude: * 300 * Please enter the longitude: * 69.947 * Incorrect Latitude or Longitude * Please enter the latitude: * 41.827 * Please enter the longitude: * 69.904 * Would you like to enter another location? * 0 * Farthest North: 41.829 * Farthest South: 41.678 * Farthest East: 69.947 * Farthest West: 69.862 * */ import java.util.Scanner; import java.lang.Math; class Lesson_20_Activity { public static void main(String[] args) { //Declare a Scanner. Scanner scan = new Scanner(System.in); //Set a flag variable, rep, to control the loop. int rep = 1; //Set up temporary variables to store the current location. double lo = 0; double la = 0; //Set up a max and min for latitude and longitude. double maxLat = -90; double minLat = 90; double maxLon = -180; double minLon = 180;

  • APCS Unit 2 Activity Guide Version 1.0 © Edhesive

    21

    //While rep == 1, continue the loop. while (rep == 1) { //Input a lat and long value. System.out.println("Please enter the latitude: "); la = scan.nextDouble(); System.out.println("Please enter the longitude: "); lo = scan.nextDouble(); //If the values are invalid, print an error, //and continue the loop. if (!(la >= -90 && la = -180 && lo maxLat) maxLat = la; if(la < minLat) minLat = la; if(lo > maxLon) maxLon = lo; if(lo < minLon) minLon = lo; System.out.println( "Would you like to enter another location? "); rep = scan.nextInt(); } }//while //Print the results. System.out.println("Farthest North: " + maxLat); System.out.println("Farthest South: " + minLat); System.out.println("Farthest East: " + maxLon); System.out.println("Farthest West: " + minLon); } }

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    1

    Lesson 22 - Activity 1

    /*

    * Term 1: Lesson 22 Coding Activity 1

    * Write the code to take a String and print it with one letter per line.

    *

    * Sample run:

    * Enter a string:

    * bought

    * b

    * o

    * u

    * g

    * h

    * t

    *

    */

    import java.util.Scanner;

    import java.lang.Math;

    class Lesson_22_Activity_One

    {

    public static void main(String[] args)

    {

    //Declare a Scanner and input a String.

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a string:");

    String h = scan.nextLine();

    //Loop through the String, printing each character.

    int i = 0;

    while (i < h.length())

    {

    System.out.println(h.charAt(i));

    i++;

    }

    }

    }

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    2

    Lesson 22 - Activity 2

    /* * Term 1: Lesson 22 Coding Activity 2 * Write the code to take a String and print it diagonally. * * Sample run: * * Enter a string: * bought * b * o * u * g * h * t * Use a tab character for every four spaces in the sample. * * Hint: You may need more than one loop. * */ import java.util.Scanner; import java.lang.Math; class Lesson_22_Activity_Two { public static void main(String[] args) { //Declare a Scanner and input a String. Scanner scan = new Scanner(System.in); System.out.println("Enter a string:"); String h = scan.nextLine(); //For each character, use a loop to print tabs //so that the ith character is preceded by //i tabs. int i = 0; while (i < h.length()) { int j = 0; while(j < i) { System.out.print("\t"); j++; } System.out.println(h.charAt(i)); i++; } } }

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    3

    Lesson 24 - Activity 1

    /* * Term 1: Lesson 24 Coding Activity 1 * Use a for loop to print all of the numbers from 23 to 89, with 10 numbers on each line. * Print one space between each number. */ import java.util.Scanner; import java.lang.Math; class Lesson_24_Activity_One { public static void main(String[] args) { //Loop from 23 to 89. for (int i = 23; i

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    4

    Lesson 24 - Activity 3

    /* * Term 1: Lesson 24 Coding Activity 3 * Input an int between 0 and 100 and print the numbers between it and 100. * If the number is not between 0 and 100 print "error". * Print 20 numbers per line. * * Sample Run 1: * * Enter a number between 0 and 100: * 30 * 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 * 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 * 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 * 90 91 92 93 94 95 96 97 98 99 100 * * * Sample Run 2: * * Enter a number between 0 and 100: * 105 * error * */ import java.util.Scanner; import java.lang.Math; class Lesson_24_Activity_Three { public static void main(String[] args) { //Declare a Scanner and input a number. Scanner scan = new Scanner(System.in); System.out.println("Enter a number between 0 and 100"); int x = scan.nextInt(); //If x is out of range, print error. if( x < 0 || x > 100) System.out.println("error"); //Otherwise, use a for loop to print every number from x to 100. //Use modular division to print 20 numbers per line. else { for(int i = x; i

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    5

    Lesson 29 - Activity 1

    /* * Term 1: Lesson 29 Coding Activity 1 * A student wants an algorithm to find the hardest spelling * word in a list of vocabulary. They define hardest by the longest word. * Write the code to find the longest word stored in an array of Strings * called list. * If several words have the same length it should print the first word * in list with the longest length. * For example, if the following list were declared: * * String list [] = {"high", "every", "nearing", "checking", "food ", * "stand", "value", "best", "energy", "add", "grand", "notation", * "abducted", "food ", "stand"}; * * It would print: * checking */ import java.util.Scanner; import java.lang.Math; class Lesson_29_Activity_One { /* Fill this list with values that will be useful for you to test. * A good idea may be to copy/paste the list in the example above. * Do not make any changes to this list in your main method. You can * print values from list, but do not add or remove values to this * variable. */ public static String [] list = {"This","is","a","test","list"}; public static void main(String[] args) { //Declare a variable to store the location of the longest String. int longest = 0; //Loop through the list, searching for a String longer than //longest. for(int i = 0; i < list.length; i++) { if(list[i].length() > list[longest].length()) longest = i; } //Print the longest value in the list. System.out.println(list[longest]); } }

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    6

    Lesson 29 - Activity 2

    /*

    * Term 1: Lesson 29 Coding Activity 2

    * Write a loop that processes an array of strings.

    * Each String should be printed backwards on its own line.

    *

    * For example, if the list contains:

    *

    * {"every", "nearing", "checking", "food", "stand", "value"}

    *

    * It should output:

    * yreve

    * gniraen

    * gnikcehc

    * doof

    * dnats

    * eulav

    */

    import java.util.Scanner;

    import java.lang.Math;

    class Lesson_29_Activity_Two

    {

    /* Fill this list with values that will be useful for you to test.

    * A good idea may be to copy/paste the list in the example above.

    * Do not make any changes to this list in your main method. You can

    * print values from list, but do not add or remove values to this

    * variable.

    */

    public static String [] list = {"sihT","si","a","tset","tsil"};

    public static void main(String[] args)

    {

    //Use a for loop to access each String in the list.

    for(int i = 0; i < list.length; i++)

    {

    //Loop through each String backwards, printing the

    //characters.

    for(int j = list[i].length() - 1; j >= 0; j--)

    System.out.print(list[i].charAt(j));

    //print a new line after each String.

    System.out.println();

    }

    }

    }

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    7

    Lesson 30 - Activity 1

    /* * Term 1: Lesson 30 Coding Activity * Due to a problem with a scanner an array of words was created * with spaces in incorrect places. Write the code to process the * list of words and trim any spaces out of the words. * * So if the list contains: * {"every", " near ing ", " checking", "food ", "stand", "value "} * * It should be changed to hold: * {"every", "nearing", "checking", "food", "stand", "value"} * * Note that this activity does not require you to print anything. * Your code should end with the array list still declared and * containing the resulting words. * */ import java.util.Scanner; class Lesson_30_Activity { /* * Your code should end with the following array modified as the * instructions above specify. You may modify the elements in * this list but make sure you do not add or remove anything from it. */ public static String [] list = {"Th is"," is","a ","t es t","li st"}; public static void main(String[] args) { //Loop through the list to access each String. for(int i = 0; i < list.length; i++) { //Declare a new String to include only the non-space

    //characters. String tmp = ""; //For each character in the current String, if it is not //a space, add it to the temporary String, tmp. for(int j = 0; j < list[i].length(); j++) if( list[i].charAt(j) != ' ') tmp += list[i].charAt(j); //Set the current String to the value of tmp. list[i] = tmp; } } }

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    8

    Lesson 1011 - Activity 1

    /* * Term 1: Lesson 1011 Coding Activity * * Input a String to represent the octal number and translate to the base ten * number. * The octal number must be 8 digits or less. * * Your program should also check that all the digits are 0 - 7, then * translate the * number to base ten. * * Sample Run 1: * Enter a number in base 8: * 1287 * ERROR: Incorrect Octal Format * * Sample Run 2: * Enter a number in base 8: * 123 * 83 * * Sample Run 3: * Enter a number in base 8: * 1111111111 * ERROR: Incorrect Octal Format * */ import java.util.Scanner; import java.lang.Math; class Lesson_1011_Activity { public static void main (String str[]) { //Set up a Scanner and input a base 8 number as a String. Scanner scan = new Scanner (System.in); System.out.println("Enter a number in base 8: "); String oct1 = scan.nextLine(); //Use a loop to check for valid input. for (int i = 0; i < oct1.length(); ++i) { //Check for invalid ith character. if(i >= 8 || !(oct1.charAt(i) >= '0' && oct1.charAt(i)

  • APCS Unit 3 Activity Guide Version 1.0 © Edhesive

    9

    //Declare an int to store the value of our base 8 number. int a = 0; //Get the highest power of 8 int highestPower = oct1.length()-1; //use a loop to sum the value of each digit, multiplied //by 8 to the power of that digit. for (int i = 0; i < oct1.length(); ++i) { a += ((oct1.charAt(i)) - 48) * Math.pow(8, highestPower-i); } //Print the result. System.out.println(a); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    1

    Lesson 32 - Activity 1

    /* * Term 1: Lesson 32 Coding Activity 1 * For the Lesson 32 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes a parameter for the number of a month * and prints the month's name. * This method must be called monthName() and it must have an integer * parameter. * Calling monthName(8) should print August to the screen. */ import java.io.*; import java.util.Scanner; class Lesson_32_Activity_One { public static void monthName(int m) { //Use if statements to check for each month individually. //Alternatively, students may create a String array and use //the variable m to access the month, as in the //following commented out code. /* * String [] months = {"January", "February", "March", "April", "May", * "June", "July", "August", "September", "October", * "November", "December"}; * return months[m - 1]; */ if (m == 1) System.out.println("January"); if (m == 2) System.out.println("February"); if (m == 3) System.out.println("March"); if (m ==4) System.out.println("April"); if (m == 5) System.out.println("May"); if (m == 6) System.out.println("June"); if (m == 7) System.out.println("July"); if (m == 8) System.out.println("August"); if (m == 9) System.out.println("September"); if (m == 10) System.out.println("October");

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    2

    if (m == 11) System.out.println("November"); if (m == 12) System.out.println("December"); } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a month number:"); int m = scan.nextInt(); System.out.println("monthName(" + m + ") prints:"); monthName(m); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    3

    Lesson 32 - Activity 2

    /* * Term 1: Lesson 32 Coding Activity 2 * For the Lesson 32 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes a parameter for the number of a month * and prints the number of days in the month. Assume that February * will always have 28 days for this activity. * This method must be called monthDays()and it must take an integer * parameter. * Calling monthDays(2) would print 28 and monthDays(9) would print 30. */ import java.io.*; import java.util.Scanner; class Lesson_32_Activity_Two { public static void monthDays(int m) { //There are three possible values for monthDays: 28, 30, or 31. //A three part if-else construction is used to return the appropriate //value. if (m == 4 || m == 6 || m == 9 || m == 11) System.out.println(30); else if (m == 2 ) System.out.println(28); else System.out.println(31); } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a month number:"); int m = scan.nextInt(); System.out.println("monthDays(" + m + ") prints:"); monthDays(m); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    4

    Lesson 32 - Activity 3

    /* * Term 1: Lesson 32 Coding Activity 3 * For the Lesson 32 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes two integer parameters and prints them in * reverse. * This method must be called swap and should take two integer parameters. * Calling swap(3, 7) would print 7 3. */ import java.io.*; import java.util.Scanner; class Lesson_32_Activity_Three { public static void swap (int a, int b) { //Print a and b in reverse order System.out.println(b + " " + a); } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter two numbers:"); int a = scan.nextInt(); int b = scan.nextInt(); System.out.println("Swap(" + a + ", " + b + ") prints:"); swap(a,b); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    5

    Lesson 32 - Activity 4

    /* * Term 1: Lesson 32 Coding Activity 4 * For the Lesson 32 activities, you will be asked to write one or * more methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that accepts a number of seconds and prints the * correct number of hours, minutes and seconds. * This method must be called realTime() and its parameter must be an * integer. * Calling realTime(6342) would print the following: * Hours: 1 * Minutes: 45 * Seconds: 42 */ import java.io.*; import java.util.Scanner; class Lesson_32_Activity_Four { public static void realTime (int s) { //There are 3600 seconds in an hour. Divide to determine the //number of hours. System.out.println("Hours: " + s / (3600) ); //Use modular division to recover the remaining seconds and //divide by 60 to convert to minutes. s = s % (3600); System.out.println("Minutes: " + s / 60); //Again, use mod to recover the remaining seconds. //Recall that s %= 60 is equivalent to s = s % 60 s %= 60; System.out.println("Seconds: " + s); } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a number of seconds:"); int s = scan.nextInt(); System.out.println("realTime(" + s + ") prints:"); realTime(s); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    6

    Lesson 33 - Activity 1

    /* * Term 1: Lesson 33 Coding Activity 1 * For the Lesson 33 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * For questions 2-5, you may want to start with the printIt method * and use it to test the other three. * Write a method that takes an array of Strings and changes of the Strings * to UPPER CASE. * This method must be called upper() and it must take a String[] parameter. * Use T1_L33_Reference_Tempate.java, which is included in this folder, * as a reference. */ import java.io.*; import java.util.Scanner; class Lesson_33_Activity_One { public static void upper(String [] a) { //Use a for loop to process each index in an array for(int i = 0; i < a.length; i++) { //At each i, change the ith string to uppercase by storing //the results of a[i].toUpperCase() in a[i]. a[i] = a[i].toUpperCase(); } } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); String [] a = new String [n]; for(int i = 0; i < n; i++) { System.out.println("Enter a String:"); a[i] = scan.next(); } System.out.println("Calling upper() on the values you entered" + " changes the array to the following:"); upper(a); for(int i = 0; i < a.length; i++) System.out.println(a[i]); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    7

    Lesson 33 - Activity 2

    /* * Term 1: Lesson 33 Coding Activity 2 * For the Lesson 33 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * For questions 2-5, you may want to start with the printIt method * and use it to test the other three. * Write a method that takes an array of ints and stores random numbers * between 10 and 99 in the array. Use Math.random() to generate * random numbers and convert them to integers between 10 and 99 inclusive. * This method must be called randomize() and it must take an int[] * parameter. */ import java.io.*; import java.util.Scanner; class Lesson_33_Activity_Two { public static void randomize(int [] a) { //This is similar to problem 1, but we are storing the result of //Math.random() in an in array instead of processing Strings. for (int i = 0; i < a.length; i++) { a[i] = (int) (Math.random()*90) + 10; } } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; randomize(a); System.out.println("First call to randomize:"); for(int i = 0; i < a.length; ++i) System.out.println(a[i]); randomize(a); System.out.println("Second call to randomize:"); for(int i = 0; i < a.length; ++i) System.out.println(a[i]); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    8

    Lesson 33 - Activity 3

    /* * Term 1: Lesson 33 Coding Activity 3 * For the Lesson 33 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * For questions 2-5, you may want to start with the printIt method * and use it to test the other three. * Write a method that takes an array of ints and prints the array on a * single line. Print one space between each number. * This method must be called printit() and it must take an int[] parameter. */ import java.io.*; import java.util.Scanner; class Lesson_33_Activity_Three { public static void printit(int [] a) { for (int i = 0; i < a.length; i++) { //Print the ith element of a followed by a single space, //using System.out.print so that all output is printed //on a single line. System.out.print(a[i] + " "); } //Print a newline after running the loop System.out.println(); } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a postivite number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; for(int i = 0; i < n; ++i) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Using printit to print an array of" + " those numbers prints the following:"); printit(a); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    9

    Lesson 33 - Activity 4

    /* * Term 1: Lesson 33 Coding Activity 4 * For the Lesson 33 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * For questions 2-5, you may want to start with the printIt method * and use it to test the other three. * Write a method that takes an array of ints and reverses the order * of the values in the array. So the array {1, 2, 3} would be changed to * {3, 2, 1} * This method must be called reverse() and it must take an int[] parameter. */ import java.io.*; import java.util.Scanner; class Lesson_33_Activity_Four { public static void reverse (int a[]) { //Create a temporary array to store the values of a int temp[] = new int[a.length]; //Use a for loop to copy a into temp for (int i = 0; i < a.length; i++) { temp[i] = a[i]; } //Use a second for loop to copy temp back into a, //but using length-1-i to access the values of //temp in reverse order. for (int i = 0; i < a.length; i++) { a[i] = temp[a.length - 1 - i]; } } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a postivite number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n];

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    10

    for(int i = 0; i < n; ++i) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Before calling reverse(a):"); printit(a); reverse(a); System.out.println("After calling reverse(a):"); printit(a); } //include printit for testing public static void printit(int [] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    11

    Lesson 33 - Activity 5

    /* * Term 1: Lesson 33 Coding Activity 5 * For the Lesson 33 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * For questions 2-5, you may want to start with the printIt method * and use it to test the other three. * Write a method that takes an array of ints, an integer value, * and an integer index.The method should insert the value at the given * index and move the values afterwards by one. * This method must be called insertValue() and must have the following * parameter types: int[], integer, integer. * Calling insertValue(a, 100, 2) would change the array {1, 2, 3, 4, 5} * to {1, 2, 100, 3, 4}. */ import java.io.*; import java.util.Scanner; class Lesson_33_Activity_Five { public static void insertValue(int a[], int value, int loc) { //This for loop starts at the end of the list and moves //backwards until it reaches loc. for ( int i = a.length - 1; i > loc; i--) { //at each step in the loop, we are shifting one element forward //in the array in order to make room for the new value. a[i] = a[i - 1]; } //Store the value after shifting the array. a[loc] = value; } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; for(int i = 0; i < n; i++) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    12

    System.out.println("You have entered the array:"); printit(a); System.out.println("Now enter a location:"); int loc = scan.nextInt(); System.out.println("And a value to insert:"); int val = scan.nextInt(); insertValue(a, val, loc); System.out.println("After calling insertValue with" + val + " and " + loc + ":"); printit(a); } //include printit for testing public static void printit(int [] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    13

    Lesson 34 - Activity 1

    /* * Term 1: Lesson 34 Coding Activity 1 * For the Lesson 34 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes an array of ints as a parameter and * returns the sum of integers in the array. * public static int sum(int [] a) * For example, sum(a); would return 6, if a = {1, 2, 3}, * or 3, if a = {1, 1, 1}. */ import java.io.*; import java.util.Scanner; class Lesson_34_Activity_One { public static int sum(int [] a) { //Declare s to store the sum int s = 0; //Loop through the array, adding each value to s for(int i =0; i < a.length; i++) { s += a[i]; } //return the sum return s; } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; for(int i = 0; i < n; i++) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Calling sum on this array returns " + sum(a)); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    14

    Lesson 34 - Activity 2

    /* * Term 1: Lesson 34 Coding Activity 2 * For the Lesson 34 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes an array of ints as a parameter * and returns the average value of the array as a double. * public static double average(int [] a) * For example, average(a) would return 2.0 * if a = {1, 2, 3} or 1.0 if a = {1, 1, 1}. */ import java.io.*; import java.util.Scanner; class Lesson_34_Activity_Two { //Use sum from the previous activity public static int sum(int [] a) { int s = 0; for(int i =0; i < a.length; i++) { s += a[i]; } return s; } public static double average(int [] a) { //Since we already have a method to sum an array, //we only need to divide that sum by the length. //Multiplying by 1.0 converts sum to a double so that the //result will be accurate. return 1.0 * sum(a)/a.length; } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n];

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    15

    for(int i = 0; i < n; i++) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Calling average on this array returns " + average(a)); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    16

    Lesson 34 - Activity 3

    /* * Term 1: Lesson 34 Coding Activity 3 * For the Lesson 34 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes an array of ints and returns * the largest value in the array. * public static int findMax(int [] a) */ import java.io.*; import java.util.Scanner; class Lesson_34_Activity_Three { public static int findMax(int []a) { //Create a variable to store the max int max = a[0]; for(int i = 0; i < a.length; i++) { //if the ith element of a is greater than the max, //then we have a new max, a[i]. if (max < a[i]) max = a[i]; } return max; } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; for(int i = 0; i < n; i++) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Calling findMax on this array returns " + findMax(a)); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    17

    Lesson 34 - Activity 4

    /* * Term 1: Lesson 34 Coding Activity 4 * For the Lesson 34 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes an array of ints * and returns the smallest value in the array. * public static int findMin(int [] a) */ import java.io.*; import java.util.Scanner; class Lesson_34_Activity_Four { public static int findMin(int []a) { //This method is identical to max, //except we reverse the comparison in our //if statement. int min = a[0]; for(int i = 0; i < a.length; i++) { if (min > a[i]) min = a[i]; } return min; } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; for(int i = 0; i < n; i++) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Calling findMin on this array returns " + findMin(a)); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    18

    Lesson 34 - Activity 5

    /* * Term 1: Lesson 34 Coding Activity 5 * For the Lesson 34 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes an array of ints * and returns a sum of only the even values. * public static int sumEven(int [] a) * For example, sumEven(a) would return 6 if a = {1, 2, 3, 4, 5}. */ import java.io.*; import java.util.Scanner; class Lesson_34_Activity_Five { public static int sumEven(int [] a) { //As in the sum method, we need a variable to add values to. int sum = 0; for(int i =0; i < a.length; i++) { //An additional if statement is used to only add //even values. if (a[i] %2 ==0) sum += a[i]; } return sum; } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; for(int i = 0; i < n; i++) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Calling sumEven on this array returns " + sumEven(a)); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    19

    Lesson 34 - Activity 6

    /* * Term 1: Lesson 34 Coding Activity 6 * For the Lesson 34 activities, you will be asked to write one or more * methods. * Use the template to write a main method that tests each of your methods, * then paste everything into the code runner box. Your submission should * begin with the first import statement and end with the final }. * Write a method that takes an array of ints and returns true if all * of the values in the array are positive. If the array contains any * negative integers, it should return false. * public static boolean allPositive(int [] a) */ import java.io.*; import java.util.Scanner; class Lesson_34_Activity_Six { public static boolean allPositive (int [] a) { for(int i = 0; i < a.length; i++) { //If a single value is negative, we return false if (a[i] < 0) return false; } //If the loop has been run, and we have not returned, then no values //were negative, so we can return true. Students may feel more //comfortable working with a flag variable, but it is worth //discussing this approach to help with understanding //return statements. return true; } //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a positive number" + " indicating the length of an array:"); int n = scan.nextInt(); int [] a = new int [n]; for(int i = 0; i < n; i++) { System.out.println("Enter any integer:"); a[i] = scan.nextInt(); } System.out.println("Calling allPositive on this array returns " + allPositive(a)); } }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    20

    Lesson 35 - Activity 1

    /* * Lesson 35 Coding Activity * Write four overloaded methods called randomize. Each method will * return a random number based on the parameters that it receives: * Write four overloaded methods called randomize. * Each method will return a random number based on the parameters that it * receives: * randomize(int min, int max) - Returns a random int between min and max * inclusive. Must have two int parameters. * randomize(int max) - Returns a random int between 0 and max inclusive. * Must have one int parameter. * randomize(double min, double max) - Returns a random double between min * and max inclusive. Must have two double parameters. * randomize(double max) - Returns a random double between 0 and max * inclusive. Must have one double parameter. * Because these methods are overloaded, they should be declared in the same * class. * To simulate this, copy all four methods into the single Code Runner box. */ import java.io.*; import java.util.Scanner; class Lesson_35_Activity { //return a random int between min and max public static int randomize(int min, int max) { return (int) (Math.random() * (max - min + 1)) + min; } public static int randomize(int max) { //Use our previous method to simplify this one return randomize (0, max); } //These two methods work in the same way, but without converting to ints //This works because all four versions of randomize use different //parameters. public static double randomize(double min, double max) { return (Math.random() * (max - min)) + min; } public static double randomize(double max) { return randomize (0, max); }

  • APCS Unit 4 Activity Guide Version 1.0 © Edhesive

    21

    //main method to test the program. This is not required by the //code runner, but is an important step in writing new methods. public static void main(String [] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a decimal minimum:"); double a = scan.nextDouble(); System.out.println("Enter a decimal maximum:"); double b = scan.nextDouble(); System.out.println("randomize(int, int) returns " + randomize((int)a, (int)b)); System.out.println("randomize(int) returns " + randomize((int)(b))); System.out.println("randomize(double, double) returns " + randomize(a, b)); System.out.println("randomize(double) returns " + randomize(b)); } }