Purpose:
Iterators, HashMap, Encoding/Decoding
Part 1: More Loops
Design methods with loops (and Iterators when appropriate) that solve the following problems. You may use the shortened for loop notation (what we call "foreach"), but be sure you understand what it does and that you can write it out using an Iterator as well.
Exercise 1:
Calculate the sum of all the numbers from 1 to a given number.
Exercise 2:
Calculate the factorial of a given number. Remember that: 5! == 5*4*3*2*1
Exercise 3:
Take an ArrayList<String> and returns a String of all the elements separated by spaces.
Exercise 4:
Determine whether or not a given number is prime. A number is prime if it is only divided evenly by 1 and itself.
For this you might want to use the modulus operator (%).Exercise 5:
Determine the largest prime number in a given ArrayList.
Part 2: Encoding and Decoding using HashMaps
We will use HashMaps in a simple fashion for now to get the idea of encoding and decoding. We will build on this with an encoding scheme in the next lab.
Exercise 6:
Design a class Crypt. This class will need two HashMaps, one to hold the encoding, and another to hold the decoding. We will encode from Characters to Integers.
Exercise 7:
Design a method addCode, which takes a character and an integer representation for that character, and adds mappings to both Maps.
Exercise 8:
Design the methods encode, which takes a Character and returns its Integer, and decode, which takes an Integer and returns its Character.
Exercise 9:
Design the overloaded methods encode, which takes a String of Characters and return a String of Integers (you will want to separate with spaces for now), and decode, which does the opposite.
Note: You will probably want to use the String function charAt(int index) and a loop with an index to get each element of the String. And for decoding, you can use split(" ") to return an array, and use a similar loop with an index to retrieve each element of the array. You can convert this into an Integer with Integer.valueOf(String s).
Test by creating a Crypt class, adding a few Character->Integer representations, then encoding and decoding a simple String containing those values.