13 Lesson 14 - Activity 1 - Weeblykeithleyslhs.weebly.com/uploads/6/9/5/2/69521249/lessons... · 2018-09-02 · 14 Lesson 14 - Activity 2 /* * Term 1: Lesson 14 Coding Activity 2 - [PDF Document] (2024)

  • 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 isnot 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 { publicstatic void main(String[] args) { //Declare a scanner and input anint. 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 toinput two integers and print * "Both are positive or zero." to thescreen, if both are positive or zero. * Print "One or both arenegative." otherwise. */ import java.util.Scanner; classLesson_14_Activity_Two { public static void main(String[] args) {//Declare a Scanner and input two integers. Scanner scan = newScanner(System.in); System.out.println("Please enter twointegers:"); int x = scan.nextInt(); int y = scan.nextInt(); //Useif-else to produce the necessary output. if(x >= 0 && y>= 0) System.out.println("Both are positive or zero."); elseSystem.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 onweb 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 255separated * by a period. * For example, 128.253.21.58 is an IPaddress. * * Write a program to enter four numbers and test if theymake up a valid IP * address. * In other words, test to see if thenumbers entered are between 0 and 255 * inclusive. * * Sample Run 1* Please enter the first octet: * 898 * Please enter the secondoctet: * 34 * Please enter the third octet: * 712 * Please enterthe fourth octet: * 45 * Octet 1 is incorrect * Octet 3 isincorrect * * * Sample Run 2 * Please enter the first octet: * 112* Please enter the second octet: * 200 * Please enter the thirdoctet: * 0 * Please enter the fourth octet: * 254 * IP Address:112.200.0.254 * */ import java.util.Scanner; classLesson_14_Activity_Three { public static void main(String[] args) {//Declare a Scanner and input four octets. Scanner scan = newScanner(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 thethird 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. intcorrect = 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. * * Whatdo 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; classLesson_17_Activity_One { public static void main(String[] args) {//Declare a Scanner and prompt for scores. Scanner scan = newScanner(System.in); System.out.println("Enter the Scores: ");//Input the first score and declare sum and count variables. inttest = scan.nextInt(); int sum = 0; int c = 0; //While the input isnot -1, increase the count, //add to the sum, and read the nextinput. 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 twonumbers. Print only the even numbers between them, * you shouldalso 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 3032 34 36 38 40 42 44 * * */ import java.util.Scanner; importjava.lang.Math; class Lesson_17_Activity_Two { public static voidmain(String[] args) { //Declare a Scanner and input two numbers.System.out.println("Enter two numbers: "); Scanner scan = newScanner(System.in); int a = scan.nextInt(); int b = scan.nextInt();//Create a new variable, start, which is a rounded //up to thenearest even number. int start = a + (a%2); //While start is inrange, 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 jobsare in demand. Right now we have a shortage * of people that can docomputer programming, and one of the fastest * growing areas of newjobs in the sector are so-called hybrid jobs. * This means youspecialize in an area like biology, * and then use computerprogramming to do your job. * * These hybrid jobs exist in thearts, sciences, * economics, healthcare, and entertainment fields.* * One of these jobs is computational biology. ComputationalBiology, * sometimes referred to as bioinformatics, is the scienceof * using biological data to develop algorithms and relations *among various biological systems. * * In this lab we are going toinvestigate the data from a * grey seal named Gracie. We’ll inputthe longitude and * latitude data from a tracking device. We wantto investigate * the farthest north, south, east and west Graciehas been. * * We will use the latitude to measure this. * Write aprogram to enter Gracie’s longitude and Latitude data. * Each timethrough the loop it should ask if you want to continue. * Enter 1to repeat, 0 to stop. * * Any value for latitude not between -90and 90 inclusive should be ignored. * * Any value for longitude notbetween -180 and 180 inclusive should be * ignored. * * * SampleRun: * * Please enter the latitude: * 41.678 * Please enter thelongitude: * 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 * Pleaseenter 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 enterthe 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 toenter another location? * 0 * Farthest North: 41.829 * FarthestSouth: 41.678 * Farthest East: 69.947 * Farthest West: 69.862 * */import java.util.Scanner; import java.lang.Math; classLesson_20_Activity { public static void main(String[] args) {//Declare a Scanner. Scanner scan = new Scanner(System.in); //Set aflag variable, rep, to control the loop. int rep = 1; //Set uptemporary 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) { //Inputa lat and long value. System.out.println("Please enter thelatitude: "); la = scan.nextDouble(); System.out.println("Pleaseenter the longitude: "); lo = scan.nextDouble(); //If the valuesare 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 liketo 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 letterper 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 totake a String and print it diagonally. * * Sample run: * * Enter astring: * bought * b * o * u * g * h * t * Use a tab character forevery four spaces in the sample. * * Hint: You may need more thanone 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 = newScanner(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 toprint all of the numbers from 23 to 89, with 10 numbers on eachline. * Print one space between each number. */ importjava.util.Scanner; import java.lang.Math; classLesson_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 between0 and 100 and print the numbers between it and 100. * If the numberis not between 0 and 100 print "error". * Print 20 numbers perline. * * 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 * 5051 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 * 70 71 7273 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 * 90 91 92 93 9495 96 97 98 99 100 * * * Sample Run 2: * * Enter a number between 0and 100: * 105 * error * */ import java.util.Scanner; importjava.lang.Math; class Lesson_24_Activity_Three { public static voidmain(String[] args) { //Declare a Scanner and input a number.Scanner scan = new Scanner(System.in); System.out.println("Enter anumber between 0 and 100"); int x = scan.nextInt(); //If x is outof range, print error. if( x < 0 || x > 100)System.out.println("error"); //Otherwise, use a for loop to printevery number from x to 100. //Use modular division to print 20numbers 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 analgorithm to find the hardest spelling * word in a list ofvocabulary. They define hardest by the longest word. * Write thecode to find the longest word stored in an array of Strings *called list. * If several words have the same length it shouldprint the first word * in list with the longest length. * Forexample, 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; classLesson_29_Activity_One { /* Fill this list with values that will beuseful for you to test. * A good idea may be to copy/paste the listin the example above. * Do not make any changes to this list inyour main method. You can * print values from list, but do not addor remove values to this * variable. */ public static String []list = {"This","is","a","test","list"}; public static voidmain(String[] args) { //Declare a variable to store the location ofthe 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 inthe 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 totest.

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

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

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

    * 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 ascanner an array of words was created * with spaces in incorrectplaces. Write the code to process the * list of words and trim anyspaces out of the words. * * So if the list contains: * {"every", "near ing ", " checking", "food ", "stand", "value "} * * It shouldbe changed to hold: * {"every", "nearing", "checking", "food","stand", "value"} * * Note that this activity does not require youto print anything. * Your code should end with the array list stilldeclared and * containing the resulting words. * */ importjava.util.Scanner; class Lesson_30_Activity { /* * Your code shouldend with the following array modified as the * instructions abovespecify. You may modify the elements in * this list but make sureyou do not add or remove anything from it. */ public static String[] list = {"Th is"," is","a ","t es t","li st"}; public static voidmain(String[] args) { //Loop through the list to access eachString. for(int i = 0; i < list.length; i++) { //Declare a newString to include only the non-space

    //characters. String tmp = ""; //For each character in thecurrent String, if it is not //a space, add it to the temporaryString, tmp. for(int j = 0; j < list[i].length(); j++) if(list[i].charAt(j) != ' ') tmp += list[i].charAt(j); //Set thecurrent 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 torepresent the octal number and translate to the base ten * number.* The octal number must be 8 digits or less. * * Your programshould also check that all the digits are 0 - 7, then * translatethe * number to base ten. * * Sample Run 1: * Enter a number inbase 8: * 1287 * ERROR: Incorrect Octal Format * * Sample Run 2: *Enter a number in base 8: * 123 * 83 * * Sample Run 3: * Enter anumber in base 8: * 1111111111 * ERROR: Incorrect Octal Format * */import java.util.Scanner; import java.lang.Math; classLesson_1011_Activity { public static void main (String str[]) {//Set up a Scanner and input a base 8 number as a String. Scannerscan = new Scanner (System.in); System.out.println("Enter a numberin base 8: "); String oct1 = scan.nextLine(); //Use a loop to checkfor 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 32activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes a parameter for thenumber of a month * and prints the month's name. * This method mustbe called monthName() and it must have an integer * parameter. *Calling monthName(8) should print August to the screen. */ importjava.io.*; import java.util.Scanner; class Lesson_32_Activity_One {public static void monthName(int m) { //Use if statements to checkfor each month individually. //Alternatively, students may create aString array and use //the variable m to access the month, as inthe //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 theprogram. This is not required by the //code runner, but is animportant step in writing new methods. public static voidmain(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 32activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes a parameter for thenumber 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 theappropriate //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 stepin writing new methods. public static void main(String [] args) {Scanner scan = new Scanner(System.in); System.out.println("Enter amonth 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 32activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes two integerparameters and prints them in * reverse. * This method must becalled swap and should take two integer parameters. * Callingswap(3, 7) would print 7 3. */ import java.io.*; importjava.util.Scanner; class Lesson_32_Activity_Three { public staticvoid swap (int a, int b) { //Print a and b in reverse orderSystem.out.println(b + " " + a); } //main method to test theprogram. This is not required by the //code runner, but is animportant step in writing new methods. public static voidmain(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 32activities, you will be asked to write one or * more methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that accepts a number of secondsand 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.*; importjava.util.Scanner; class Lesson_32_Activity_Four { public staticvoid realTime (int s) { //There are 3600 seconds in an hour. Divideto determine the //number of hours. System.out.println("Hours: " +s / (3600) ); //Use modular division to recover the remainingseconds and //divide by 60 to convert to minutes. s = s % (3600);System.out.println("Minutes: " + s / 60); //Again, use mod torecover the remaining seconds. //Recall that s %= 60 is equivalentto 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 = newScanner(System.in); System.out.println("Enter a number ofseconds:"); 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 33activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * For questions 2-5, you may want to start withthe printIt method * and use it to test the other three. * Write amethod that takes an array of Strings and changes of the Strings *to UPPER CASE. * This method must be called upper() and it musttake a String[] parameter. * Use T1_L33_Reference_Tempate.java,which is included in this folder, * as a reference. */ importjava.io.*; import java.util.Scanner; class Lesson_33_Activity_One {public static void upper(String [] a) { //Use a for loop to processeach index in an array for(int i = 0; i < a.length; i++) { //Ateach i, change the ith string to uppercase by storing //the resultsof 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 = newScanner(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 33activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * For questions 2-5, you may want to start withthe printIt method * and use it to test the other three. * Write amethod 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 99inclusive. * This method must be called randomize() and it musttake an int[] * parameter. */ import java.io.*; importjava.util.Scanner; class Lesson_33_Activity_Two { public staticvoid randomize(int [] a) { //This is similar to problem 1, but weare storing the result of //Math.random() in an in array instead ofprocessing Strings. for (int i = 0; i < a.length; i++) { a[i] =(int) (Math.random()*90) + 10; } } //main method to test theprogram. This is not required by the //code runner, but is animportant step in writing new methods. public static voidmain(String [] args) { Scanner scan = new Scanner(System.in);System.out.println("Enter a positive number" + " indicating thelength 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 33activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * For questions 2-5, you may want to start withthe printIt method * and use it to test the other three. * Write amethod that takes an array of ints and prints the array on a *single line. Print one space between each number. * This methodmust be called printit() and it must take an int[] parameter. */import java.io.*; import java.util.Scanner; classLesson_33_Activity_Three { public static void printit(int [] a) {for (int i = 0; i < a.length; i++) { //Print the ith element ofa followed by a single space, //using System.out.print so that alloutput 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 = newScanner(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" + " thosenumbers 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 33activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * For questions 2-5, you may want to start withthe printIt method * and use it to test the other three. * Write amethod that takes an array of ints and reverses the order * of thevalues 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 takean int[] parameter. */ import java.io.*; import java.util.Scanner;class Lesson_33_Activity_Four { public static void reverse (inta[]) { //Create a temporary array to store the values of a inttemp[] = new int[a.length]; //Use a for loop to copy a into tempfor (int i = 0; i < a.length; i++) { temp[i] = a[i]; } //Use asecond for loop to copy temp back into a, //but using length-1-i toaccess the values of //temp in reverse order. for (int i = 0; i< a.length; i++) { a[i] = temp[a.length - 1 - i]; } } //mainmethod to test the program. This is not required by the //coderunner, but is an important step in writing new methods. publicstatic void main(String [] args) { Scanner scan = newScanner(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 anyinteger:"); a[i] = scan.nextInt(); } System.out.println("Beforecalling 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 33activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * For questions 2-5, you may want to start withthe printIt method * and use it to test the other three. * Write amethod that takes an array of ints, an integer value, * and aninteger index.The method should insert the value at the given *index and move the values afterwards by one. * This method must becalled insertValue() and must have the following * parameter types:int[], integer, integer. * Calling insertValue(a, 100, 2) wouldchange the array {1, 2, 3, 4, 5} * to {1, 2, 100, 3, 4}. */ importjava.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 //backwardsuntil 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 = newScanner(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:"); intval = scan.nextInt(); insertValue(a, val, loc);System.out.println("After calling insertValue with" + val + " and "+ loc + ":"); printit(a); } //include printit for testing publicstatic 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 34activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes an array of ints as aparameter and * returns the sum of integers in the array. * publicstatic int sum(int [] a) * For example, sum(a); would return 6, ifa = {1, 2, 3}, * or 3, if a = {1, 1, 1}. */ import java.io.*;import java.util.Scanner; class Lesson_34_Activity_One { publicstatic 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 = newScanner(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 34activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes an array of ints as aparameter * 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; classLesson_34_Activity_Two { //Use sum from the previous activitypublic static int sum(int [] a) { int s = 0; for(int i =0; i <a.length; i++) { s += a[i]; } return s; } public static doubleaverage(int [] a) { //Since we already have a method to sum anarray, //we only need to divide that sum by the length.//Multiplying by 1.0 converts sum to a double so that the //resultwill be accurate. return 1.0 * sum(a)/a.length; } //main method totest the program. This is not required by the //code runner, but isan important step in writing new methods. public static voidmain(String [] args) { Scanner scan = new Scanner(System.in);System.out.println("Enter a positive number" + " indicating thelength 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 anyinteger:"); a[i] = scan.nextInt(); } System.out.println("Callingaverage 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 34activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes an array of ints andreturns * the largest value in the array. * public static intfindMax(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 greaterthan 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. Thisis not required by the //code runner, but is an important step inwriting new methods. public static void main(String [] args) {Scanner scan = new Scanner(System.in); System.out.println("Enter apositive 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 arrayreturns " + 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 34activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes an array of ints *and returns the smallest value in the array. * public static intfindMin(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 thecomparison 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 = newScanner(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 34activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes an array of ints *and returns a sum of only the even values. * public static intsumEven(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. intsum = 0; for(int i =0; i < a.length; i++) { //An additional ifstatement is used to only add //even values. if (a[i] %2 ==0) sum+= a[i]; } return sum; } //main method to test the program. This isnot required by the //code runner, but is an important step inwriting new methods. public static void main(String [] args) {Scanner scan = new Scanner(System.in); System.out.println("Enter apositive 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 arrayreturns " + 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 34activities, you will be asked to write one or more * methods. * Usethe template to write a main method that tests each of yourmethods, * then paste everything into the code runner box. Yoursubmission should * begin with the first import statement and endwith the final }. * Write a method that takes an array of ints andreturns true if all * of the values in the array are positive. Ifthe 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 { publicstatic boolean allPositive (int [] a) { for(int i = 0; i <a.length; i++) { //If a single value is negative, we return falseif (a[i] < 0) return false; } //If the loop has been run, and wehave not returned, then no values //were negative, so we can returntrue. Students may feel more //comfortable working with a flagvariable, but it is worth //discussing this approach to help withunderstanding //return statements. return true; } //main method totest the program. This is not required by the //code runner, but isan important step in writing new methods. public static voidmain(String [] args) { Scanner scan = new Scanner(System.in);System.out.println("Enter a positive number" + " indicating thelength of an array:"); int n = scan.nextInt(); int [] a = new int[n]; for(int i = 0; i < n; i++) { System.out.println("Enter anyinteger:"); a[i] = scan.nextInt(); } System.out.println("CallingallPositive 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 methodscalled randomize. Each method will * return a random number basedon the parameters that it receives: * Write four overloaded methodscalled randomize. * Each method will return a random number basedon the parameters that it * receives: * randomize(int min, int max)- Returns a random int between min and max * inclusive. Must havetwo int parameters. * randomize(int max) - Returns a random intbetween 0 and max inclusive. * Must have one int parameter. *randomize(double min, double max) - Returns a random double betweenmin * 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 methodsare overloaded, they should be declared in the same * class. * Tosimulate this, copy all four methods into the single Code Runnerbox. */ import java.io.*; import java.util.Scanner; classLesson_35_Activity { //return a random int between min and maxpublic static int randomize(int min, int max) { return (int)(Math.random() * (max - min + 1)) + min; } public static intrandomize(int max) { //Use our previous method to simplify this onereturn randomize (0, max); } //These two methods work in the sameway, but without converting to ints //This works because all fourversions of randomize use different //parameters. public staticdouble 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 = newScanner(System.in); System.out.println("Enter a decimal minimum:");double a = scan.nextDouble(); System.out.println("Enter a decimalmaximum:"); 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)); } }

13 Lesson 14 - Activity 1 - Weeblykeithleyslhs.weebly.com/uploads/6/9/5/2/69521249/lessons... · 2018-09-02 · 14 Lesson 14 - Activity 2 /* * Term 1: Lesson 14 Coding Activity 2 - [PDF Document] (2024)
Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 5488

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.