Share
Java Programming

Course Outline

Week 1
Week 2
Week 3
Week 4
Week 5
Week 6
Week 7

Arrays

  • Declaring and Initializing an Array
  • Declaring and Using Arrays of Objects
  • Manipulating Arrays of Strings
  • Searching an Array
  • Passing Arrays to and Returning Arrays from Methods
Week 8

SponsoredAdvertise

Declaring and Initializing an Array

 

In order to see the importance of array, we will liketo consider this problem.

 

Write a Java program that reads five numbers, finds their sum, and prints the numbers in reverse order.

 

Solution


import java.util.Scanner;


public class Main
{

      public static void main(String[] args) {
            // TODO Auto-generated method stub
            double num_1,num_2,num_3,num_4,num_5,sum;
            Scanner input = new Scanner(System.in);
            //Ask user to enter the first number
            System.out.println("Enter number 1");
            num_1 = input.nextDouble();
            System.out.println("Enter number 2");
            num_2 = input.nextDouble();
            System.out.println("Enter number 3");
            num_3 = input.nextDouble();
            System.out.println("Enter number 4");
            num_4 = input.nextDouble();
            System.out.println("Enter number 5");
            num_5 = input.nextDouble();
            sum = num_1+num_2+num_3+num_4+num_5;
            System.out.println(num_1+" + "+num_2+" + "+num_3+" + "+num_4+" + "+num_5+" = "+sum);
            System.out.println("The numbers in reverse order is: "+num_5+", "+num_4+" , "+num_3+" , "+num_2+" , "+num_1);
      }
}


Thisprogram works fine. However, if you need to read 100 (or more) numbers and printthem in reverse order, you would have to declare 100 variables and write manyinput statements. Thus, for large amounts of data, this type of program is not desirable.

 

The above problem could also be solved using the concept of an array which will be considering this week.


The numbers will be stored in the array so that it can be printed in the reverse order. The above problem will later be solved by the end of this lesson.

 

An array is a collection of a fixed number of components all of the same data type.

 

You declare an array variable in the same way you declare any simple variable, but you insert a pair of square brackets after the type. For example, to declare an array of double values to hold numbers, you can write the following:

 

double[] numbers;

 

Thus in general, an array is declared as:

 

datatype[] nameOfArray;

 

Then you create the array with the following statement:


nameOfArray= new data type[sizeOfArray];

 

Thus to declare an array that will contain 1000 double data types, we can write the statement below:

 

double[]numbers = new double[1000];

 

Initializing an array

 

An array is initialized using the index of the array. Array index starts from 0 and ends at the size of the array – 1. Thus for an array of size 5, the index will be 0, 1, 2, 3 and 4.


An array of name num of size 8 will have the following index.

 

  num[0] num[1] num[2] num[3] num[4] num[5] num[6] num[7]
Index 0 1 2 3 4 5 6 7

 

 

To assign a value to a particular index of the array, the equal to operator is used just like assigning a value of a variable.

 

Thus:

 

arrayName[Index] = value;

 

Thus to assign 10 to the array (numbers) at an index of 0, the statement will be:

 

numbers[0] = 10;

 

and 11 to index 1, the statement will be:

 

numbers[1] = 11;

 

You can also assign non default values to array elements upon creation. To initialize an array, you use a list of values separated by commas and enclosed within curly braces. For example, if you want to create an array named tenMult and store the first six multiples of 10 within the array, you can declare tenMult as follows:

int[] tenMult = {10, 20, 30, 40, 50, 60};

 

Notice the semicolon at the end of the statement. You don’t use a semicolon following a method’s closing curly brace, but you do use one following the closing brace of an array initialization list.

 

Providing values for all the elements in an array is called populating the array. When you populate an array upon creation, you do not give the array a size—the size is assigned based on the number of values you place in the initializing list. For example, the tenMult array just defined has a size of 6. Also, when you initialize an array, you do not need to use the keyword new; instead, new memory is assigned based on the length of the list of provided values.


In Java, you cannot directly initialize part of an array. For example, you cannot create an array of 10 elements and initialize only five; you either must initialize every element or none of them.

 

Accessing the values in the array

 

Just like assigning value to array, you can access the value using the array index.

 

Thus to access the value stored in the numbers array at index 1, we can write:

 

double num = numbers[1];

 

To access the value of the array at multiple indexes, we can use a loop.

 

For example to access the numbers array to the fifth index we can write

 

for(int i=0;i<5;i++){

            System.out.println(numbers[i]);

}

 

To access all the values of the array, the loop starts at 0 to the array size -1

 

For instance if the array is 10, we can access all the10 values in the array with the for loop below:

 

for(int i=0;i < 10; i++){

            System.out.println(arrayName[i]);

}

 

Now let’s write the Java program above with the concept of the array.

 

Write a Java program that reads 10 numbers, finds their sum, and prints the numbers in reverse order.


Solution


import java.util.Scanner;


public class Main
{

      public static void main(String[] args) {
            // TODO Auto-generated method stub
            double[] num = new double[10];
            Scanner in = new Scanner(System.in);
            double sum = 0;
            //Get the input and store them in the array so you can later print in reverse order
            for(int i=0;i<10;i++){
                  System.out.println("Enter a number:");
                  num[i] = in.nextDouble();
                  sum = sum+num[i];
            }
            //Display the sum
            System.out.println("The sum is "+sum);
            System.out.println("**************");
            System.out.println("REVERSE ORDER");
            System.out.println("**************");
            //Loop through the array from the last index to index 0
            for(int i=9;i>=0;i--){
                  System.out.println(num[i]);
            }   
      }
}


Declaring and using array of objects

 

Statement:

 

ObjectName[] nameOfObject = new ObjectName[sizeOfArray];

 

You have to create the instance of the object at each index of the array. Thus:

 

nameOfObject[0] = new ObjectName();

nameOfObject[1] = new ObjectName();

 

If the object has a constructor, you make sure you pass the necessary input data for the constructor.

 

You can call the methods of the object for each of the created objects at their index.

 

For example if the object has a method call getName(),the objectName at index of 0 can call the getName() method as:

 

objectName[0].getName();

 

Create a course object which has the course name, course teacher and course code. Use a constructor to set the object values and get methods to retrieve the set values.

 

Solution


Course.java


public class Course {
      String name, teacher, code;
      public Course(String name,String teacher, String code){
            this.name = name;
            this.teacher = teacher;
            this.code = code;
      }
      public String getName(){
            return name;
      }
      public String getTeacher(){
            return teacher;
      }
      public String getCode(){
            return code;
      }
}


Create a course array of size 5 and print out the course name, teacher and code for each of the created course object.


Main.java


import java.util.Scanner;
public class Main
{
      public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            Course[] course = new Course[5];
            //Get the course details and create object of the course
            for(int i=0;i<5;i++){
                  System.out.println("Enter course name:");
                  String name = in.nextLine();
                  System.out.println("Enter course teacher:");
                  String teacher = in.nextLine();
                  System.out.println("Enter course code:");
                  String code = in.nextLine();
                  course[i] = new Course(name,teacher,code);
            }
            //Now display course info
            System.out.println("***********************");
            System.out.println("        COURSES      ");
            System.out.println("***********************");
            for(int i=0;i<5;i++){
                  System.out.println("Name:"+course[i].getName());
                  System.out.println("Teacher:"+course[i].getTeacher());
                  System.out.println("Code:"+course[i].getCode());
            }

      }
}


Manipulating Arrays of Strings

 

As with any other object, you can create an array ofStrings. For example, you can store three fruit names as follows:

 

String[] fruits = {"Mango", "Banana","Apple"};

 

We can create a fruit guessing game where we ask auser to guess the name of the fruit in the basket. If the entered fruit is inthe array, we inform the user that guess is wrong, otherwise we inform the userthat guess is right.

 

Create the fruit guessing program.

 

Main.java


import javax.swing.JOptionPane;
public class Main
{
      public static void main(String[] args) {
            String[] fruits = {"Mango","Orange","Apple"};
            String guess = JOptionPane.showInputDialog(null,"Guess the fruit in the basket");
            int right = 0;
            for(int i=0;i<3;i++){
                  if(guess.equalsIgnoreCase(fruits[i])){
                        right++;
                  }
            }
            if(right>0){
                  JOptionPane.showMessageDialog(null,"Your guess is right");
            }else{
                  JOptionPane.showMessageDialog(null,"Your guess is wrong");
            }
      }
}


Searching an array

 

Just like the above guess game, to search through anarray to see if the search value exist in the array, you have to loop throughthe array. You have to declared a variable and initialized it to a value. Whileyou loop through the array, you change the value of that variable when you finda content in the array which matches the search key word.

 

Example

 

The following are the names of students in a class.Kofi, Ama, Adjei, Bortey, Mohammed and Adzovi. Save the names in an array andwrite a program that ask the user to search for a name in the class. If thename exist, you alert the user that name found in the class else, alert theuser that search returned no result.

 

SAMPLE CODE


import javax.swing.*;;
public class Main
{
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String[] names = new String[6];
            names[0] = "Kofi";
            names[1] = "Ama";
            names[2] = "Adjei";
            names[3] = "Bortey";
            names[4] = "Mohammed";
            names[5] = "Adzovi";
            String name = JOptionPane.showInputDialog("Enter a name to search");
            int found = 0;
            for(int i=0;i<names.length;i++){
                  if(name.equalsIgnoreCase(names[i])){
                        found = 1;
                  }
            }
            if(found==1){
                  //An item was found alert user
                  JOptionPane.showMessageDialog(null,name+" is found in the class");
            }else{
                  JOptionPane.showMessageDialog(null,"No student in the class by name "+name);
            }
      }
}


 


MULTI-DIMENSIONAL ARRAY

 

An array with more than one dimension is called amulti-dimensional array. We will only consider two dimensional array. Thesyntax for a two dimensional array is:

 

datatype [][] nameOfArray = newdatatype[sizeOfRows][sizeOfColumns];

 

To assign a value to a particular row and column weuse the syntax:

 

nameOfArray[rowIndex][columnIndex] = value to assign to that position;

 

To access a value from a particular position we use the syntax:

 

nameOfArray[rowIndex][columnIndex];

 

Example


You have been contacted to develop a simple software to calculate the salary of a staff. Before a staff uses the software, the staff must login with any of the following login details. Once any of the login details is correct, the staff should be given access to the application, otherwise the staff should be alert incorrect login details. The hourly rate is Ghc 8.5 and the tax rate is 15%.

 

Username Password
pass PASSWORD
admin root
2019 12345

 

FORMULA

 

Gross Salary = Hourly Rate x Hours Worked

Tax = Gross Salary x Tax Rate / 100

Salary = Gross Salary - Tax

 

SOLUTION

 

We can use two dimensional array to develop the abovelogin feature,

 

row/column 0 1
0 pass PASSWORD
1 admin root
2 2019 12345

 

The datatype of the array will be String since is a text input.

 

The rowSize is 3 and the column size is 2.

 

We can therefore declare the array as:

 

String[][] login_details = new String[3][2];

 

We can assign each of the values at the various positions as:

 

login_details[0][0] = “pass”;

login_details[0][1] = “PASSWORD”;

login_details[1][0] = “admin”;

login_details[1][1] = “root”;

login_details[2][0] = “2019”;

login_details[2][1] = “12345”;

 

Now you can use a for loop to iterate the array and see if the login details the user enters matches both the username and the password on each rows. If at least one matches, we give access to the user.

 

The complete code is shown below:


import javax.swing.*;;
public class Main
{
      //Set constant values
      final static double HOURLY_RATE = 8.5;
      final static double TAX_RATE = 15;
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String[][] login_details = new String[3][2];
            login_details[0][0] = "pass";
            login_details[0][1] = "PASSWORD";
            login_details[1][0] = "admin";
            login_details[1][1] = "root";
            login_details[2][0] = "2019";
            login_details[2][1] = "12345";
            //Get the username and password from the user
            String username = JOptionPane.showInputDialog("Enter your username");
            String password = JOptionPane.showInputDialog("Enter your password");
            //Iterate through the array to see if the password is correct or not
            int grant_access = 0;
            for(int i=0;i<3;i++){
             if((login_details[i][0].equalsIgnoreCase(username))&&(login_details[i][1].equals(password))){
                        //If the username and the password matches the user inputs, set grant_access to 1
                        grant_access = 1;
                  }
            }
            //Now check the value of grant_access to see if it has changed or still 0
            if(grant_access==1){
                  //Since grant_access is 1, means the username and password is correct so show the application
                  String sHours = JOptionPane.showInputDialog("Enter the hours worked");
                  double hrs = Double.parseDouble(sHours);
                  double gross_salary = hrs*HOURLY_RATE;
                  double tax = gross_salary*TAX_RATE/100;
                  double salary = gross_salary - tax;
                  //Output the result
                  JOptionPane.showMessageDialog(null,"Hourly Rate: GHC "+HOURLY_RATE+"\nTax Rate: "+TAX_RATE+"%\nGross Salary: GHC "+gross_salary+"\nTax: GHC "+tax+"\nSalary: Ghc "+salary);
            }else{
                  JOptionPane.showMessageDialog(null, "Incorrect login details");
            }
      }
}


NOTE

 

We use the equalsIgnoreCase method to compare the entered username with the usernames at the username column because usernames are not case sensitive but password is so we didn't use to compare the password.

 

We also use the && operator because both the username and the password at the column at row index i must match what the user enters before an access can be granted.

 

Assignment


Create a class for employee and take the employee details and store them in array. Display the stored information. Ask a user to search for employee and iterate through the employee array to see if the name entered for the search matches any of the employee names stored in the array. Before a staff uses this application, he/she must login before being asked to enter the employee details and see other features of the application.

SponsoredAdvertise