Lesson 6: Data Structures, Arrays, and Strings
Activity 21: Finding the Smallest Number in an Array
Solution:
Set up the main method in a new class file known as ExampleArray:
public class ExampleArray { public static void main(String[] args) { } }
Create an array of 20 numbers:
double[] array = {14.5, 28.3, 15.4, 89.0, 46.7, 25.1, 9.4, 33.12, 82, 11.3, 3.7, 59.99, 68.65, 27.78, 16.3, 45.45, 24.76, 33.23, 72.88, 51.23};
Set the minimum float as the first number
double min = array[0];
Create a for loop to check all the numbers in the array
for (doublefloat f : array) { }
Use if to test each number against the minimum. If it is smaller than the minimum then make that number the new minimum:
if (f < min) min = f; }
After the loop completes, print out the minimum number:
System.out.println("The lowest number in the array is " + min); } }
The full code should look like this.
public class ExampleArray { public static void main(String[] args) { double[] array = {14.5, 28.3, 15.4, 89.0, 46.7, 25.1, 9.4, 33.12, 82, 11.3, 3.7, 59.99, 68.65, 27.78, 16.3, 45.45, 24.76, 33.23, 72.88, 51.23}; double min = array[0]; for (double f : array) { if (f < min) min = f; } System.out.println("The lowest number in the array is " + min); } }
Activity 22: Calculator with Array of Operators
Solution:
Create a class Operators that will contain the logic of determining what operator to use based out of a String. In this class create a public constant field default_operator that is going to be an instance of the Operator class. Then create another constant field called operators of type array of Operator and initialize it with an instance of each of the operators you have:
public class Operators { public static final Operator DEFAULT_OPERATOR = new Operator(); public static final Operator [] OPERATORS = { new Division(), new Multiplication(), DEFAULT_OPERATOR, new Subtraction(), };
In the Operators class, add a public static method called findOperator that receives the operator as a String and return an instance of Operator. Inside it iterate over the possible operators array and, using the matches method for each operator, return the selected operator, or the default one if it didn't match any of them:
public static Operator findOperator(String operator) { for (Operator possible : OPERATORS) { if (possible.matches(operator)) { return possible; } } return DEFAULT_OPERATOR; } }
Create a new CalculatorWithDynamicOperator class with three fields: operand1 and operator2 as double and operator of type Operator:
public class CalculatorWithDynamicOperator { private final double operand1; private final double operand2; // The current operator private final Operator operator;
Add a constructor that receives three parameters: operand1 and operand2 of type double and operator as a String. In the constructor, instead of having an if-else to select the operator, use the Operators.findOperator method to set the operator field:
public CalculatorWithDynamicOperator(double operand1, double operand2, String operator) { this.operand1 = operand1; this.operand2 = operand2; this.operator = Operators.findOperator(operator); } public double operate() { return operator.operate(operand1, operand2); }
Add a main method where you call the Calculator class multiple times and print the results:
public static void main (String [] args) { System.out.println("1 + 1 = " + new CalculatorWithDynamicOperator(1, 1, "+").operate()); System.out.println("4 - 2 = " + new CalculatorWithDynamicOperator(4, 2, "-").operate()); System.out.println("1 x 2 = " + new CalculatorWithDynamicOperator(1, 2, "x").operate()); System.out.println("10 / 2 = " + new CalculatorWithDynamicOperator(10, 2, "/").operate()); } }
Activity 23: Working with ArrayList
Solution:
Import ArrayList and Iterator from java.util:
import java.util.ArrayList; import java.util.Iterator;
Create a new class called StudentsArray:
public class StudentsArray extends Student{
In the main method define an ArrayList of Student objects. Insert 4 student instances, instantiated with different kinds of constructors we created earlier:
public static void main(String[] args){ ArrayList<Student> students = new ArrayList<>(); Student james = new Student(); james.setName("James"); Student mary = new Student(); mary.setName("Mary"); Student jane = new Student(); jane.setName("Jane"); Student pete = new Student(); pete.setName("Pete"); students.add(james); students.add(mary); students.add(jane); students.add(pete);
Create an iterator for your list and print the name of each student:
Iterator studentsIterator = students.iterator(); while (studentsIterator.hasNext()){ Student student = (Student) studentsIterator.next(); String name = student.getName(); System.out.println(name); }
Clear all the students:
students.clear(); } }
The final code should look like this:
import java.util.ArrayList; import java.util.Iterator; public class StudentsArray extends Student{ public static void main(String[] args){ ArrayList<Student> students = new ArrayList<>(); Student james = new Student(); james.setName("James"); Student mary = new Student(); mary.setName("Mary"); Student jane = new Student(); jane.setName("Jane"); students.add(james); students.add(mary); students.add(jane); Iterator studentsIterator = students.iterator(); while (studentsIterator.hasNext()){ Student student = (Student) studentsIterator.next(); String name = student.getName(); System.out.println(name); } students.clear(); } }
The output is as follows:
Activity 24: Input a String and Output Its Length and as an Array
Solution:
Import the java.util.Scanner package:
import java.util.Scanner;
Create a public class called NameTell and a main method:
public class NameTell { public static void main(String[] args) {
Use the Scanner and nextLine to input a string at the prompt "Enter your name:"
System.out.print("Enter your name:"); Scanner sc = new Scanner(System.in); String name = sc.nextLine();
Count the length of the string and find the first character:
int num = name.length(); char c = name.charAt(0);
Print an output:
System.out.println("\n Your name has " + num + " letters including spaces."); System.out.println("\n The first letter is: " + c); } }
The output is as follows:
Activity 25: Calculator Reads from Input
Solution:
Create a new class called CommandLineCalculator with a main() method in it:
import java.util.Scanner; public class CommandLineCalculator { public static void main (String [] args) throws Exception { Scanner scanner = new Scanner(System.in);
Use an infinite loop to keep the application running until the user asks to exit.
while (true) { printOptions(); String option = scanner.next(); if (option.equalsIgnoreCase("Q")) { break; }
Collect the user input to decide which action to execute. If the action is Q or q, exit the loop:
System.out.print("Type first operand: "); double operand1 = scanner.nextDouble(); System.out.print("Type second operand: "); double operand2 = scanner.nextDouble(); Operator operator = Operators.findOperator(option); double result = operator.operate(operand1, operand2); System.out.printf("%f %s %f = %f\n", operand1, operator.operator, operand2, result); System.out.println(); } }
If the action is anything else, find an operator and request two other inputs that will be the operands covering them to double:
private static void printOptions() { System.out.println("Q (or q) - To quit"); System.out.println("An operator. If not supported, will use sum."); System.out.print("Type your option: "); } }
Call the operate method on the Operator found and print the result to the console.
Activity 26: Removing Duplicate Characters from a String
Solution:
Create a Unique class as follows:
public class Unique {
Create a new method removeDups called that takes and returns a string. This is where our algorithm will go. This method should be public and static:
public static String removeDups(String string){
Inside the method, check whether the string is null, empty, or has a length of 1. If any of these cases are true, then just return the original string since there checking is not needed:
if (string == null) return string; if (string == "") return string; if (string.length() == 1) return string;
Create a string called result that is empty. This will be a unique string to be returned:
String result = "";
Create for loop from 0 to the length of the string passed into the method. Inside the for loop, get the character at the current index of the string. Name the variable c. Also create a boolean called isDuplicate and initialize it to false. When we encounter a duplicate, we will change it to true.
for (int i = 0; i < string.length() ; i++){ char c = string.charAt(i); boolean isDuplicate = false;
Create another nested for loop from 0 to the length() of result. Inside the for loop, also get the character at the current index of result. Name it d. Compare c and d. If they are equal, then set isDuplicate to true and break. Close the inner for loop and go inside the first for loop. Check if isDuplicate is false. If it is, then append c to result. Go outside the first for loop and return the result. That concludes our algorithm:
for (int j = 0; j < result.length(); j++){ char d = result.charAt(j); if (c == d){ //duplicate found isDuplicate = true; break; } } if (!isDuplicate) result += ""+c; } return result; }
Create a main() method as follows:
public static void main(String[] args){ String a = "aaaaaaa"; String b = "aaabbbbb"; String c = "abcdefgh"; String d = "Ju780iu6G768"; System.out.println(removeDups(a)); System.out.println(removeDups(b)); System.out.println(removeDups(c)); System.out.println(removeDups(d)); } }
The output is as follows:
The full code is as follows:
public class Unique { public static String removeDups(String string){ if (string == null) return string; if (string == "") return string; if (string.length() == 1) return string; String result = ""; for (int i = 0; i < string.length() ; i++){ char c = string.charAt(i); boolean isDuplicate = false; for (int j = 0; j < result.length(); j++){ char d = result.charAt(j); if (c == d){ //duplicate found isDuplicate = true; break; } } if (!isDuplicate) result += ""+c; } return result; } public static void main(String[] args){ String a = "aaaaaaa"; String b = "aaabbbbb"; String c = "abcdefgh"; String d = "Ju780iu6G768"; System.out.println(removeDups(a)); System.out.println(removeDups(b)); System.out.println(removeDups(c)); System.out.println(removeDups(d)); } }
The output is as follows: