/** * This activity will walk you through writing basic code in Java. You will see how to define methods, * work with different data types, write conditionals, write loops, and work with arrays. We will not * work with any more advanced class features of Java * * Read the file from the top down. Some problems will have prewritten code. Make sure you * read and understand what each line is for and doing, and ask questions if you do not understand. */ public class JavaBasics { /* * Each problem in this activity will be a different method. This main class * runs the methods defined in each problem so that you run the file and see what your code does. * When you have completed a problem, uncomment out that respective problem's print statement. */ public static void main(String[] args) { // System.out.println("Problem 0: " + problem0()); // System.out.println("Problem 1: " + Integer.toString(problem1())); // System.out.println("Problem 2: " + Integer.toString(problem2(3, 5))); // System.out.println("Problem 3: " + problem3()); // System.out.println("Problem 4: " + problem4()); // System.out.println("Problem 5: The 3rd through 9th characters of \"Hamburglar!\" are " + problem5("Hamburglar!")); // System.out.println("Problem 6: " + problem6(1)); // System.out.printf("Problem 7: 1 is %s, 2 is %s, 3 is %s, and 6 is %s \n", problem7(1), problem7(2), problem7(3), problem7(6)); // System.out.println("Problem 8: The numbers from 1 to 20 sum to " + problem8(20)); // System.out.println("Problem 9: Racecar backwards is " + problem9("Racecar")); // System.out.println("Problem 10: The default int array with 5 elements is " + problem10(5)); // System.out.println("Problem 11: Your explicit array was " + Arrays.toString(problem11())); // System.out.println("Problem 12: The integers in {5, 6, 2, 3} sum to " + problem12(new int[] {5, 6, 2, 3})); // System.out.println("Problem 13: The numbers 1 to 5 are " + Arrays.toString(problem13(5))); // System.out.println("Problem 14: The numbers from 1 to 20 still sum to " + problem14(20)); } /* * Problem 0 : How This Activity Works * In order to avoid compile errors, most problem methods in this file * throw an UnsupportedOperationException. When working on a specific problem * delete the line throwing the exception and uncomment the return statement below it. */ private static String problem0() { // Remove the line below throw new UnsupportedOperationException("Remove This Line and Uncomment The Return Below"); // Uncomment the line below (delete the // symbol) // return "I did it!"; // Don't forget to uncomment the print statement in main for this problem! // Run the program to make sure it prints out "I did it!" } /* * Problem 1 : Declaring Variables * This method will show you how to declare variables * This method should output the number 12. Follow the instructions below. */ private static int problem1() { int a; //Declares that the variable a exists and is an int. a becomes the default int value of 0 a = 5; //Reassigns a to be 5 // We can do this all on one line: // int a = 5; // Declare an int variable named b below, assign it a value so that this function returns 12. // Do this all on one line. Then you can uncomment the return statement. throw new UnsupportedOperationException("Remove This Line"); // return a + b; // Don't forget to uncomment the print statement in main for this problem! } /* * Problem 2 : Method Arguments * We can declare variables in a method's signature. These are the inputs to the function * and are usable within the method body. This method currently takes in one input, an integer, * that is referred to in the body of the code as c. * * Add a second int input named d to this method. If you run the file after removing * the exception and uncommenting the return and the call in main it should print "8" */ private static int problem2(int c) { throw new UnsupportedOperationException("Remove This Line"); // return c + d; } /* * Problem 3 : Method Return Type * * The type listed before the method name is the return type of the function. * When we call a method, we get something of the return type back. * Add a return statement to this method and return anything you want of it's return type. */ private static String problem3() { throw new UnsupportedOperationException("Remove This Line"); } /* * Problem 4 : Calling Methods * * We can call methods defined in a file inside of other methods we write. We do this by simply * writing their name. * * We can call public methods defined in other files by using the . operator, either: * 1) If the method is not static, we use . after the specific instance of that type (e.g. "Hello".charAt(5)) * 2) If the method is static, we use . after the class name (e.g. ) * * In this problem we will call the method you defined above, and return a String * This String will be the number of characters in the string cubed. * For example, if problem3() returned "Banana!", problem4() would return "343" since * "Banana!" has 7 characters, and 7^3 = 343. Notice "343" is a String, not an int. * * */ private static String problem4() { // Call your problem3() method and assign it to a String variable called p3 // Call the instance (non-static) length() String method on p3, assign it to a variable numChars // Call the static pow() method of the Math class on numChars to cube it. Assign thi value // to a variable named numCubed. You can hover over pow to read the documentation, // or you can go to https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/lang/Math.html // You will get back a double (decimal). You need to cast it to an int by writing (int), e.g. // int example = (int) 5.6; throw new UnsupportedOperationException("Remove This Line"); // We use the static method toString() of the Integer class to convert an int to a String //return Integer.toString(numCubed); } /* * Problem 5: Declaring your own method * * Write your own private static method named problem5() that takes in a String and returns a String. * The output String will be the 3rd through 9th characters of the input. You should look in the String * class documentation for the method substring to help you do this. * * For example problem5("0123456789") will return "2345678". * Remember that the index of the 1st character of a String is 0. * Pay attention to which indexes of substring are inclusive vs exclusive * * Read the String documentation (https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/lang/String.html) * to find a method to help you do this. */ // Declare your own method here as described above /* * Problem 6 : Conditionals * * In this problem we will see how to use conditionals. This method should return * "Galinda" if the method is given an even int and "Elphaba" an odd int. * */ private static String problem6(int n) { // The syntax for a basic if-else conditional is // if (condition) { // ... // } else { // .. // } // where condition is whatever Boolean condition you want // The below code always returns Galinda. Replace true with // a condition to check whether n is even or odd. // Even numbers are multiples of 2, and remember we can use modulo (%) to // check if a number is a multiple of another. if (true) { return "Galinda"; } else { return "Elphaba"; } // If you do this correctly, Elphaba should print when run. // In the void method, try changing the input to problem6 to get it to print Galinda again. } /* * Problem 7 : else if * We can make more complicated conditionals with else if statements. * * A number is "threeven" if it is divisible by 3. Write a private static method called problem7 * that, given an int, returns the String "even" if the input is is even, "threeven" if it is divisible by 2, * "both" if it is both even and threeven, and "neither" if it is neither. * * You will need to use ``else if" in conjunction with the Boolean operators && (and), || (or), and ! (not): * * if () { * ... * } else if () { * ... * } else { * ... * } * * You can chain as many else ifs as you want! */ // Write your method problem7() here /* * Problem 8 : For Loops * * To write a for loop in java we have to follow a specific syntax: * * for (statementA ; statementB ; statementC) { * ... * } * * Where: * statementA is a declaration of a loop variable * statementB is a condition involving the loop variable * statementC is an update to the loop variable that occurs at the end of the iteration * * Finish the method below, which when given the int n, sums the numbers from 1 to n. * For example, problem8(9) = 45, since 1 + 2 + 3 + ... + 9 = 45 * */ public static int problem8(int n) { int output = 0; // this variable will be our output for (int i = 1; i <= n; i = i + 1) { // Add code here to sum up the numbers // When the loop starts, i = 1 and we should add 1 to output // At the next loop iteration, i = 2, and so we should add 2 to the output } // Make sure you understand what each part of the for loop declaration is doing! return output; } /* * Problem 9 : Loops over Strings * * Finish the method below which reverses the input. * For example, problem9("Banana") outputs "ananaB" * You just need to declare the loop, your temp variable should be called i */ public static String problem9(String s) { String output = ""; // the output string will start as the `empty string', the string with no characters // Write a for loop that starts at the end of the works backwards. // Hint 1: How do you start at the end of the string? // Hint 2: When do you stop the loop? // Hint 3: How does your loop variable change after every iteration? // Remember that the 1st character of a string is at position 0 // The last character of a string is at position n-1, where n is the string's length // Use the following to concatenate the characters as you go. // output = output.concat(s.charAt(i)) return output; } /* * Problem 10 : Declaring Arrays * * In Java we can declare an array of any type by writing [] after the name of the * Type. * * Follow the comments to finish the method below, which returns the String representation of * a default int array of length n */ private static String problem10(int n) { // Declare and initialize a default int array variable named arr of size n // Remember we use the new command to initialize a default array // e.g. new String[i]; initializes a default String array of size i throw new UnsupportedOperationException("Remove This Line"); // Arrays.toString() above converts arr into a readable String // The method arr.toString() returns gibberish // To use it we must first write: // import java.util.Arrays; // at the top of this file //return Arrays.toString(arr); } /* * Problem 11 : Declaring Arrays Explicitly * * Using "new arr[i];" to declare an array fills the array with default values * We can explicitly provide values using {} * * For example, * int[] example = {1, 2, 3, 4}; * Or if we are not assigning it to a variable: * new int[] {1, 2, 3, 4}; */ private static String[] problem11() { // Declare an initialize a String array named arr that contains four Strings of your choosing. throw new UnsupportedOperationException("Remove This Line"); // return arr; } /* * Problem 12 : Accessing Arrays * * We access the (i+1)th element of an array by writing [i] after the name of the array. * Finish the method below that sums the values of an int array * For example problem12({3, 2, 3, 4}) returns 12 since 3 + 2 + 3 + 4 = 12 */ private static int problem12(int[] arr) { int output = 0; // Write a for loop that "traverses" the array from the beginning to end // Inside your loop, access the stored value at that position and increase output by that amount // Remember that you use .length to get the length of an array (no parentheses) return output; } /* * Problem 13 : Assigning Values to Arrays * * We assign values to an array by accessing them and using =. For example, * arr[3] = 10; * makes the 4th element of arr 10 * * Write a private static method named problem13 that, given an int n, returns an int array of length n whose elements * are 1, 2, 3, ... n * * Declare an int array named output and initialize it as a default array of the correct size. * Use a for loop to loop through the entries of output and replace the 0s with the correct value * After your loop, return output */ // Write your code here: /* * Problem 14 : Combining Methods * * Use the methods problem12() and problem13() to finish the method below * This method will do the same as problem8, which when given int n, * outputs the sum of the numbers from 1 to n. * */ private static int problem14(int n) { throw new UnsupportedOperationException("Remove This Line"); } }