Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java Fundamentals

You're reading from   Java Fundamentals A fast-paced and pragmatic introduction to one of the world's most popular programming languages

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789801736
Length 408 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (5):
Arrow left icon
Miles Obare Miles Obare
Author Profile Icon Miles Obare
Miles Obare
Basheer Ahamed Fazal Basheer Ahamed Fazal
Author Profile Icon Basheer Ahamed Fazal
Basheer Ahamed Fazal
Rogério Theodoro de Brito Rogério Theodoro de Brito
Author Profile Icon Rogério Theodoro de Brito
Rogério Theodoro de Brito
Gazihan Alankus Gazihan Alankus
Author Profile Icon Gazihan Alankus
Gazihan Alankus
Vinicius Isola Vinicius Isola
Author Profile Icon Vinicius Isola
Vinicius Isola
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Java Fundamentals
Preface
1. Introduction to Java FREE CHAPTER 2. Variables, Data Types, and Operators 3. Control Flow 4. Object-Oriented Programming 5. OOP in Depth 6. Data Structures, Arrays, and Strings 7. The Java Collections Framework and Generics 8. Advanced Data Structures in Java 9. Exception Handling Appendix

Lesson 6: Data Structures, Arrays, and Strings


Activity 21: Finding the Smallest Number in an Array

Solution:

  1. Set up the main method in a new class file known as ExampleArray:

    public class ExampleArray {
      public static void main(String[] args) {
      }
    }
  2. 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};
  3. Set the minimum float as the first number

    double min = array[0];
  4. Create a for loop to check all the numbers in the array

    for (doublefloat f : array) {
    }
  5. 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;
    }
  6. 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:

  1. 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(),
        };
  2. 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;
        }
    
    }
  3. 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;
  4. 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);
        }
  5. 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:

  1. Import ArrayList and Iterator from java.util:

    import java.util.ArrayList;
    import java.util.Iterator;
  2. Create a new class called StudentsArray:

    public class StudentsArray extends Student{
  3. 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);
  4. 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);
           }
  5. 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:

    Figure 6.30: Output of the StudentsArray class

    Figure 6.31: Output of the NameTell class

Activity 24: Input a String and Output Its Length and as an Array

Solution:

  1. Import the java.util.Scanner package:

    import java.util.Scanner;
  2. Create a public class called NameTell and a main method:

    public class NameTell
    {
      public static void main(String[] args)
      {
  3. 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();
  4. Count the length of the string and find the first character:

    int num = name.length();
    char c = name.charAt(0);
  5. 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:

  1. 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);
  2. 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;
                }
  3. 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();
            }
        }
  4. 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:

  1. Create a Unique class as follows:

    public class Unique {
  2. 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){
  3. 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;
  4. Create a string called result that is empty. This will be a unique string to be returned:

    String result = "";
  5. 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;
  6. 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;
       }
  7. 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:

    Figure 6.32: Output of Unique class

    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:

    Figure 6.33: Output of Unique class

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image