CSC224 Apr10

slide version

single file version

Contents

  1. Loops
  2. Infinite Loops
  3. Off By 1
  4. Arrays
  5. Array Declarations
  6. Array Instances
  7. Default Values
  8. Default Values Assigned
  9. Example: array of basic elements
  10. Example (array of reference elements)
  11. The length member
  12. Array index Checking
  13. Arrays are Classes, but ...
  14. Array Store Checking
  15. for loop Variant for arrays
  16. Initial values of an Array
  17. Loops and scope of variables
  18. Scope: Example 1
  19. Scope: Example 2
  20. Local versus Instance Variables
  21. Example
  22. Avoid This Error!
  23. Using a Loop with String Sentinel
  24. Converting String to int.
  25. Example 1
  26. Example 2
  27. Wrapper Classes
  28. Wrapper Classes and Conversions
  29. The break and continue Statements
  30. Assigning one Array to Another
  31. ArrayList
  32. Example
  33. Example ( main method)
  34. Example (an initialization method)
  35. Example (a printArrayList method)
  36. Comparison of arrays and ArrayList
  37. Two dimensional arrays
  38. Example
  39. The main method
  40. The printArray2 method

Loops[1] [top]

Three loop statement types:

I. while-loop

 while( boolean expression ) 
 {
   body
 }

II. for-loop

 for( initializer ; boolean expression ;  update)
 {
    body
 }

III. do-while

 do 
 {
   body
 } while(boolean expression);
    

Infinite Loops[2] [top]


I.

 int i = 1;
 int a = 1;
 int b = 1;
 while( i < 100 ) 
 {
   System.out.println(a);
   int old_a = a;
   a = a + b;
   b = old_a;

 }

II.

int sum = 0;
for(int i = 1; i <= 100; i++)
{
   i = sum;
   sum = sum + i;
}

III.

for(int n = 10; n > 0; n++) 
{
   System.out.println(n);
}
System.out.println("Blast off!");

Off By 1[3] [top]

Initial value of 0 or 1?

Use < or <=?

The wrong choice(s) can cause the number of repetitions of a loop body to be off by 1. Here is an example.

Problem: Select as many items as possible so that the total weight is <= a specified target weight.

Is the loop in the code below correct or is it off by 1?

import java.util.Scanner;
public class PackingApp
{
 public static void main(String[] args)
 {
  int[] wt = {1, 2, 3, 5, 9, 15, 15, 16, 20};
  int targetWeight;
  Scanner in = new Scanner(System.in);

  targetWeight = in.nextInt();                             
  int k = 0;   // Number of items packed so far            
  int sum = 0; // Total Weight of packed items             

  while( sum <= targetWeight ) 
  {
    sum += wt[k];
    k++;
  }
  System.out.printf("target weight = %d, " +
		    "packed weight = %d, " +
		    "number items packed = %d\n",
		    targetWeight, sum, k);
 }
}

Arrays[4] [top]

Array Declarations[5] [top]

Examples:

      int[] iarray;
      double[] darray;
      String[] sarray;
      BigInteger[] biarray;
    

Array Instances[6] [top]

Examples:

      int[] iarray = new int[5];
      double[] darray = new double[10];
      String[] sarray = new String[5];
      BigInteger[] biarray = new BigInteger[10];
    

Default Values[7] [top]

Each type has a default value.

The default value for any reference (class) type is null.

The default value for any integer basic type is 0

When are variables automatically assigned the default value for their types?

Default Values Assigned[8] [top]

Default values are used to initialize variables in these cases:

  1. Variables declared in a class.
  2. Elements of an array when an array instance is created.

Default values are not used to initialize variables automaticaly:

Example: array of basic elements[9] [top]

      int[] ia = new int[5];  
    

The declaration means we have 5 integer variables:

      ia[0], ia[1], ia[2], ia[3], ia[4]
    

Each of these int variables is automatically initialized to the default value for type int.

So, for example, ia[3] is 0

Example (array of reference elements)[10] [top]

      String[] sa = new String[5];  
    

The declaration means we have 5 Strin variables:

      sa[0], sa[1], sa[2], sa[3], sa[4]
    

Each of these int variables is automatically initialized to the default value for type String.

So, for example, sa[3] is null

The length member[11] [top]

The number of elements that an array can hold is stored by an array and can be accessed.

    public void static main(String[] args)
    {
      String[] str = new String[5];

      str[0] = "one";
      str[1] = "two";
      str[2] = "three";
      str[3] = "four";
      str[4] = "five";

      // str.length is 5

      for(int i = 0; i < str.length; i++) {
         System.out.println(str[i]);
      }
    

Array index Checking[12] [top]

If an index is out of range, this is checked at run time.

    1   
    2   public class ex2
    3   {
    4     
    5     public static void main(String[] args)
    6     {
    7       String str[] = new String[5];
    8       str[0] = "one";
    9       str[1] = "two";
   10       str[2] = "three";
   11       str[3] = "four";
   12       str[4] = "five";
   13   
   14       for(int i = 0; i <= str.length; i++) {
   15         System.out.println(str[i]);
   16       }
   17   
   18     }
   19   
   20   }

Output:
one
two
three
four
five
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
      at ex2.main(ex2.java:15)

Arrays are Classes, but ...[13] [top]

All classes inherit the toString method:

      String toString()
    

but...

    1   
    2   public class ex2
    3   {
    4     
    5     public static void main(String[] args)
    6     {
    7       String str[] = new String[5];
    8       str[0] = "one";
    9       str[1] = "two";
   10       str[2] = "three";
   11       str[3] = "four";
   12       str[4] = "five";
   13   
   14       System.out.println(str);
   15     }
   16   }

Output:
Ljava.lang.String;@19821f
    

Array Store Checking[14] [top]

Storing a value in an array at run time causes a check that the type stored is compatible with the element type of the array.

The code below compiles without errors, but when it is run we get:

Exception in thread "main" java.lang.ArrayStoreException:
      java.lang.Integer
      at ex3.main(ex3.java:10)

    
    1   public class ex3
    2   {
    3     
    4     public static void main(String[] args)
    5     {
    6       Object[] s = new String[3];  // A String is an Object
    7   
    8       s[0] = "hello";
    9       s[1] = "goodbye";
   10       s[2] = new Integer(42);      // An Integer is an Object, but is not a String
   11   
   12       for(int i = 0; i < s.length; i++) {
   13         System.out.println(s[i]);
   14       }
   15     }
   16   
   17   }

for loop Variant for arrays[15] [top]

A special form of the for loop is valid for accessing the elements of an array without explicitly using a subscript:

Each time through the for loop at lines 13 - 15, x gets the next value in the array a.

    1   
    2   public class ex4
    3   {
    4     
    5     public static void main(String[] args)
    6     {
    7       Random r = new Random();
    8       int a[] = new int[5];
    9   
   10       for(int i = 0;  i < a.length; i++) {
   11         a[i] = r.nextInt(1000);
   12       }
   13       for(int x: a) {                    
   14         System.out.println(x);
   15       }
   16       
   17     }
   18   
   19   }

Initial values of an Array[16] [top]

An array instance can be initialized when the array is created:

      // In a declaration
      int[] x = {2, 5, 8};
or
      int[] x = new int[] {2, 5, 8};

or

      int[] x;

      x = new int[] {2, 5, 8};

    

Loops and scope of variables[17] [top]

The scope of a declaration is the part of code where the declared variable can be referenced.

Scope: Example 1[18] [top]

Compile Error at line 12.

The scope of the declaration of i at line 7 is lines 7 - 10; that is, this i is only accessible on those lines.

    1   /**
    2    * Returns the index in array s such that s[i] is equal to x
    3    * or returns -1 if there is no such index.
    4    */
    5   public int indexOf(String[] s, String x)
    6   {
    7      for(int i = s.length - 1; i >= 0; i--) {
    8         if (x.equals(s[i])) {
    9            break;
   10         }
   11      }
   12      return i;
   13   }

Scope: Example 2[19] [top]

Variable Scope
x Lines 4 - 21
y Lines 5 - 21
xcoord Lines 7 - 10
    1	public class Point
    2	{
    3	   private int x;
    4	   private int y;
    5	
    6	   public Point(int xcoord, int ycoord)
    7	   {
    8	      x = xcoord;
    9	      y = ycoord;
   10	   }
   11	
   12	   public int getX()
   13	   {
   14	     return x;
   15	   }
   16	
   17	   public int getY()
   18	   {
   19	     return y;
   20	   }
   21	
   22	}

Local versus Instance Variables[20] [top]

Example[21] [top]

This is the same example as earlier, but using a for-loop instead of a while-loop and checking that the index variable, k, is within bounds.

Where is the error? What addition to the loop condition would fix this error?


  int[] wt = {1, 2, 3, 5, 9, 15, 15, 16, 20};
  int targetWeight;
  Scanner in = new Scanner(System.in);

  targetWeight = in.nextInt();                               

  int sum = 0; // Total Weight of packed items               

  for(int k = 0; k < wt.length && sum < targetWeight; k++)
  {
    sum += wt[k];
  }
  System.out.printf("target weight = %d, " +
		    "packed weight = %d, " +
		    "number items packed = %d\n",
		    targetWeight, sum, k);

Avoid This Error![22] [top]

What is the output of the following:


 int sum = 0;
 int i;

 for(i = 1; i <= 10; i++);
     sum += i;

 System.out.println("sum = " + sum);

Using a Loop with String Sentinel[23] [top]

Suppose a program needs to read integer values from user input.

If -1 is not valid input for the program, it could be used as a sentinel indicating end of input.

A more general approach is to allow the user to enter a String such as "quit" or "exit".

How can we write a loop to repeatedly read integers from a user until the user enters "quit"?

Answer: Read the input as a string. If it is "quit", then stop reading.

If the input string is not "quit", convert it to an integer, process it, and repeat.

Converting String to int.[24] [top]

    Scanner in = ...

    String input = in.next();
    int n;

    n = Integer.parseInt(input);

The static parseInt method may throw a NumberFormatException if the string in input cannot be converted to an int.

This not a checked exception. Should the call to parseInt be in a try block of a try...catch construct?

Example 1[25] [top]

Sample Execution:
Input integers will added. Type quit to stop and get the total.

Enter an integer or quit: 1
Enter an integer or quit: two
Exception in thread "main" java.lang.NumberFormatException: For input string: "two"
      at java.lang.NumberFormatException.forInputString(Unknown Source)
      at java.lang.Integer.parseInt(Unknown Source)
      at ex3.main(ex3.java:15)
    1	import java.util.Scanner;
    2	public class ex3
    3	{
    4	  
    5	  public static void main(String[] args)
    6	  {
    7	    Scanner in = new Scanner(System.in);
    8	    String input;
    9	
   10	    greeting();
   11	    int sum = 0;
   12	    System.out.print("Enter an integer or quit: ");
   13	    input = in.next();
   14	    while(!input.equals("quit")) {
   15	      int n = Integer.parseInt(input);
   16	      sum += n;
   17	      System.out.print("Enter an integer or quit: ");
   18	      input = in.next();
   19	    }
   20	    System.out.printf("Total = %d\n", sum);
   21	
   22	  }
   23	
   24	  public static void greeting()
   25	  {
   26	    String msg = 
   27	      "Input integers will added. Type quit to stop and get the total.";
   28	    System.out.printf("\n%s\n\n", msg);
   29	  }
   30	}

Example 2[26] [top]

Sample Execution:
Input integers will added. Type quit to stop and get the total.

Enter an integer or quit: 1
Enter an integer or quit: two
Invalid input: two
Enter an integer or quit: 2
Enter an integer or quit: quit
Total = 3
    
import java.util.Scanner;
public class ex4
{
  
  public static void main(String[] args)
  {
    Scanner in = new Scanner(System.in);
    String input;

    greeting();
    int sum = 0;
    System.out.print("Enter an integer or quit: ");
    input = in.next();
    while(!input.equals("quit")) {
      try {
        int n = Integer.parseInt(input);
        sum += n;
      } catch(NumberFormatException e) {
        System.out.printf("Invalid input: %s\n", input);
      }
      System.out.print("Enter an integer or quit: ");
      input = in.next();
    }
    System.out.printf("Total = %d\n", sum);

  }

  public static void greeting()
  {
      // ... unchanged 
  }
}

Wrapper Classes[27] [top]

Each of the basic types has a corresponding "wrapper" class that contains a single data member of the basic type.

Some Java data structures and methods require a class type. In order to use these with basic types, create an instance of the corresponding wrapper class passing the basic value to the constructor.

For example, to "wrap" the basic int value 5:

      Integer N = new Integer(5);

      // N.intValue() is 5. 
    

Wrapper Classes and Conversions[28] [top]

Basic Type Wrapper Class Type Static Conversion Method
byte Byte byte Byte.parseByte(String s)
int Integer int Integer.parseInteger(String s)
float Float float Float.parseFloat(String s)
double Double double Double.parseDouble(String s)
      String input = "5";
      int n;

      n = Integer.parseInt("5");

      // n has value 5, not the string "5".
    

The break and continue Statements[29] [top]


 Scanner in = new Scanner(System.in);
 String strval;
 int sum = 0;
 int count = 0;
 int n;

 while( true )
 {
   System.out.println("Enter a integer value or 'quit' to stop");
   strval = in.next();
   if ( strval.startsWith("q") ) {
      break;
   }

   try {
      n = Integer.parseInt(strval);
      count++;
   } catch(NumberFormatException e) {
     System.out.printf("%s is not a valid integer. Try again.\n", strval);
     continue;
   }
   sum += n;
 }
 System.out.printf("sum of %d input integers is = %d\n", count, sum);

Assigning one Array to Another[30] [top]

Assigning one array to another doesn't create a copy array.

It just makes both variables reference the one and only array.

To make a copy of an array requires 2 steps:


public static void main(String[] args)
  {
    int[] a = {1,2,3};
    int[] b;
    int[] c;

    // Assign a to b; Still only one array
    b = a;


    // Create a copy of a
    // step (1)
    c = new int[a.length];

    // step (2)
    for(int i = 0; i < a.length; i++) {
      c[i] = a[i];
    }
  }

ArrayList[31] [top]

Arrays don't grow automatically.

The last valid index of an array A is A.length - 1

ArrayIndexOutOfBoundsException will be thrown if you try to simply insert a new value into an array beyond the last valid index.

The Java ArrayList type overcomes this limitation.

However, ArrayList is not an "array". You can't use an index to access elements of an ArrayList.

Instead you must use the methods in the ArrayList class.

The elements stored in an ArrayList must be a reference type.

Example[32] [top]

Generate 10 random integers and store them in an ArrayList.

Then print the integers.

Example ( main method)[33] [top]

The element type to be stored in the ArrayList should be enclosed in <>

There is no need to specify the size of the ArrayList, it grows as needed when elements are added.

    1     public static void main(String[] args)
    2     {
    3       ArrayList<Integer> al = new ArrayList<Integer>();
    4       Random r = new Random();
    5   
    6       init(al);
    7       printArrayList(al);
    8   
    9     }

Example (an initialization method)[34] [top]

Line 10: The add method checks and increases the storage for the ArrayList if necessary.

The new value is added to the end of the ArrayList.

    1     public static void init(ArrayList<Integer> a)
    2     {
    3       Random r = new Random();
    4       Scanner in = new Scanner(System.in);
    5   
    6       System.out.print("How many random integers: ");
    7       int n = in.nextInt();
    8   
    9       for(int i = 0; i < n; i++) {
   10         a.add(r.nextInt(101));
   11       }
   12     }

Example (a printArrayList method)[35] [top]

The ArrayList doesn't allow an index (with []), but instead you use the ArrayList Integer get(int i) method for the same purpose - to access the i-th element.

The first element is at i = 0, similar to an ordinary array.

    1     public static void printArrayList(ArrayList<Integer> a)
    2     {
    3       for(int i = 0; i < a.size(); i++) {
    4         System.out.printf("%3d. %d\n", i, a.get(i));
    5       }
    6     }

Comparison of arrays and ArrayList[36] [top]

item array ArrayList
declaration Integer[] arr; ArrayList<Integer> al
create instance arr = new Integer[5]; al = new ArrayList<Integer>();
storing values arr[0] = 5;
arr[1] = 60;
arr[0] = 50;
al.add(5);
al.add(60);
al.set(0, 50);
getting a stored value int x = arr[0]; int x = al.get(0);
number of elements int sz = arr.length; int sz = al.size();
increment a stored value arr[0] = arr[0] + 1; al.set(0, al.get(0) + 1);

Two dimensional arrays[37] [top]

A two dimensional array has a specified number of rows.

Each row has a specified number of elements.

Rows can be displayed on separated lines and the row elements line up in columns.

In Java two dimensional arrays are really arrays where the element type is also an array.

But we think of the two dimensional array as a having elements of the type of individual elements in each row.

Example[38] [top]

Generate a two dimensional array of characters with 3 rows and 5 columns.

Initialize each element with a random upper case letter.

Print the two dimensional array in 3 rows of output ( and 5 columns).

The main method[39] [top]

Line 3: delcares and creates the two dimensional array.

Line 5: jumble.length is the number of rows

jumble[0] is the entire first row. jumble[1] is the entire second row, etc., jumble[0][0] is the first character in row 0, jumble[1][0] is the first character in row 1.

Line 6: jumble[0].length is the number of elements in row 0. This is the same as jumble[1].length since all rows have the same number of elments (5). This is also the number of columns.

Line 7: This expression will generate a random letter in the range 'A' - 'Z'.

      (char) ('A' + r.nextInt(26))
    
    1     public static void main(String[] args)
    2     {
    3       char jumble[][] = new char[3][5];  // 3 rows, 5 columns
    4       Random r = new Random();
    5       for(int row = 0; row < jumble.length; row++) {
    6         for(int col = 0; col < jumble[0].length; col++) {
    7           jumble[row][col] = (char) ('A' + r.nextInt(26));
    8         }
    9       }
   10   
   11       printArray2(jumble);
   12   
   13     }

The printArray2 method[40] [top]

The spacing in the output is due to the printf statement at line 6:

    1   
    2     public static void printArray2(char a[][])
    3     {
    4       for(int i = 0; i < a.length; i++) {
    5         for(int j = 0; j < a[0].length; j++) {
    6           System.out.printf("%3c", a[i][j]);
    7         }
    8         System.out.println();
    9       }
   10     }

Sample output:

  B  O  L  F  K
  V  R  W  H  R
  C  D  C  M  Q