Tuesday, January 12, 2016

APLesson_10: ArrayLists


APLesson_10: Non-Static Arrays


Standard arrays in Java are “static” or fixed in length, meaning you set the size of your array when you initialize it. You must know the size of your Array beforehand, and it cannot be changed. This is because the Array class does not include methods that provide this functionality to its objects.



ArrayLists

ArrayList is part of the List class in Java. ArrayList objects also contain a list of objects in an index, but carry the following advantages over arrays:



  • The size of the ArrayLists can shrink or grow.
  • Items can be added or removed from an ArrayList
  • You can print ArrayLists directly with a simple println() statement



However, you must be aware that ArrayLists can only contain objects, so primitive datatypes like int and boolean need to be stored as Integer and Boolean objects.

Below is an example of declaring an ArrayList.
/**You need to import Arraylist first*/
import java.util.ArrayList;

/**Declare the array*/
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<String> list2 = new ArrayList<String>();

System.out.println("list1 size: " + list1);
System.out.println("list2 size: " + list2);

Output:
list1 size: []
list2 size: []

ArrayList Methods
Most of the advantages of ArrayLists comes from the variety of methods the class provides to manipulate your lists.

ArrayList.add(x)
Once your ArrayList is declared, you can add values. The size of the ArrayList will increase automatically with each value added.

// add(x)...
// adds x to the end of the array
list1.add(1);
list1.add(2);
list1.add(3);
list2.add("a");
list2.add("b");
list2.add("c");

System.out.println("List1 with numbers...\n" + list1);
System.out.println("List2 with letters...\n" + list2);

Output:
List1 with numbers...
[1, 2, 3]
List2 with numbers…
[a, b, c]

ArrayList.size()
Returns the length of the ArrayList. This is different from arrays because size() is a method in the ArrayList class. Do not forget to use the parentheses when you call it.

System.out.println("Length of list1..." + list1.size());
System.out.println("Length of list2..."+ list2.size());

Output:
Length of list1... 3
Length of list2... 3

ArrayList.get(x)
//get(x)
// returns the value at a given index x...
int number = list1.get(2);
System.out.println(number);

Output: 3

ArrayList.set(x)
//set(x, y)
// overwrites the value at an index x with y
list1.set(1, 8);
System.out.println(list1);

list2.set(2, "z");
System.out.println(list2);

Output:
[1, 8, 3]
[a, b, z]

ArrayList.remove(x)
//remove(x)
//deletes the value at position x from the list
list1.remove(list1.indexOf(3));
System.out.println(list1);

list2.remove(list2.indexOf(“a”));
System.out.println(list2);

Output:
[1, 8]
[b, z]

Splitting Strings into Arrays

You can use the split("") method to split up the character values in a String and create an array from these values.

//split(" ")
//parses the values from a String into an array, ignoring
//the value in parentheses, called the delimiter

String letters = "a b c d e f g";
String[] lets = letters.split(" ");


Arrays Methods

Here is a refresher for some of the Arrays methods you will be using in your labs.  In order to use the following methods, you must import the Arrays class in Java.

import java.util.Arrays;

Arrays.toString()

//Arrays.toString()
//parses the Array in parentheses into a String
System.out.println(Arrays.toString(lets));

Output:
[a, b, c, d, e, f, g]

Arrays.asList(array)

asList()
//Converts the Array to an Arraylist
Arrays.asList(lets);
ArrayList<String> letterList = new ArrayList<String>    (Arrays.asList(lets));
System.out.println(letterList);

Output:
[a, b, c, d, e, f, g]


Integer Methods

Java's Integer class wraps a primitive int datatype into an Integer object. The int data becomes a "field" or the parameter for the Integer object that sets the value of an instance variable. Integer object contain a number of methods that will be useful to us in the future.

Integer.parseInt()

Integer.parseInt()
//converts numbers in a String to an integer
String nums = "1 2 3 4 5 6 7 8 9";
System.out.println(Integer.parseInt(nums.substring(4,5)));

//if you count the spaces, the number 3 is @ position 4
   Output: 3

Putting it All Together

You can combine a number of the methods above to develop some complex algorithms. Look through the exercises below for hints.

// you can start with the string "nums" from above
// and split() it into an Array
String[] digits = nums.split(" ");

//convert the numbers to ints and add them
// to an ArrayList
ArrayList<Integer> numList = new ArrayList<Integer>();
for(int i = 0; i < digits.length; i++)
{
  numList.add(Integer.parseInt(digits[i]));
}

// Print the ArrayList
System.out.println(numList);

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

// You can now use the numbers in the array in mathematical
// operations. The following loop sums all the values in
// numList.....

int output = 0;
for (int i=0; i<numList.size(); i++)
{
  output += numList.get(i);
}

System.out.println(output);

Output: 45






APLab_10

Ex_01: KeepComposites
This program will search through an ArrayList and remove all prime numbers, keeping only the composite numbers. A composite number is divisible by at least 1 number other than 1 and itself.

  1. Declare an Array with the following numbers, called “numbers”
2,6,8,9,10,12,13,15,17,24,55,66,78,77,79

  1. Use the Arrays.asList() method to store the values in an ArrayList called “nums”

  1. gFactor() method take integer n as parameter
    • For each number from 2 to  n
      • If n is divisible by the iterator
        • Return 1
    • Otherwise return 0


  1. removePrimes() method
    • For loop: from 0 to size of nums
      • If gFactor (@param nums @ i) returns 0
        • Remove i from nums
        • Subtract 1 from i




Ex_02: Expression Solver
This program will allow you to enter compound equations involving addition, subtraction, multiplication, and division.

main() method
  1. Take user input for an equation
  2. Enter the equation into an ArrayList called “equation”
  3. print doEquation(with equation as a parameter)

doEquation() method
  1. take ArrayList() equation as parameter
    1. While i is less than size of equation
      • If equation at i is a “*” or “/”
        • If equation @ i is a “*”
          • Set equation @ i to equation @ i-1 * equation @ i+1
        • Otherwise
          • Set equation @ i to equation @ i-1 / equation @ i+1
        • Remove equation @ i-1
        • Remove equation @ i
      • Add 1 to i

  1. While i is less than size of equation
    • If equation at i is a “+” or “-”
      • If equation @ i is a “+”
        • Set equation @ i to equation @ i-1 + equation @ i+1
      • Otherwise
        • Set equation @ i to equation @ i-1 - equation @ i+1
      • Remove equation @ i-1
      • Remove equation @ i
    • Add 1 to i

  1. Return equation

Monday, October 12, 2015

String Methods

String Objects
Recall or review from Lesson_02 that Strings are not just primitive data types. They are in fact objects that have special consideration, allowing them to act like primitive data in some ways. However, there are many situations in which Strings will behave differently than other datatypes. 

When you create a String in Java...

    String name = "James Brown"

You are not really setting a String called name equal to "James Brown". You are creating a new object of the String class that contains the "James Brown" String....

    String name = new String ("James Brown");

The difference is that the String "James Brown" that we put into name can never be changed. It gets it's own permanent memory address for as long as the program is running. You are able to set name equal to a new String...

    name = "Superman"

But "James Brown" is here forever (as long as the program is running), and if we set other variables equal to "James Brown", they will all be referring to the same String. 

    String supaBad = "James Brown"; //=========+
    String soulMan = "James Brown"; //=========+==>all refer to the 
    String godFatherSoul = "James Brown"; //===+    same String

Because of this property, String objects are said to be "immutable", or unable to be changed. 


Grades in Review

Open up your Lab 10 and review Exercise_01. Here we defined the grade values without taking user inputs. Why did we do this? Would the program work if we took user inputs? 
In the Grades class, the calcPoints() method, uses the "==" operator to compare the two grade String objects. 

In the runner, our grade[X] String objects are set manually



This allows the immutability of Strings to work in our favor. For example, if we set history to "A", then the "A" in the calcPoints() method would be referring to the same "A" String object, and the condition letterGrade == "A" would evaluate to true



But the "==" operator doesn't quite work how we would expect. It does not compare the value of the two objects, but simply evaluates if two objects  refer to the same data. 

Therefore, when we take a user input for history.....



we are not setting it to "A" directly. We are setting it to the return value of next() from the Scanner object keyboard, that may or may not get an input of "A". So if we were to evaluate history == "A", we would get a return of false, even if we input "A" when prompted.  

We are then passing history through the constructor into the variable letterGrade, and the condition letterGrade == "A" returns false. 


  

In fact, no matter what combination of letter grades you input, all the conditions in the calcPoints() method will all evaluate to false, giving us a GPA of 0..... ALWAYS!!! 




String Methods

As objects of the class java.lang.String, Strings in Java have methods that we can use to manipulate and change how the String data is presented.  


equals()

In order to take user inputs in a program like Grades, we need a way to compare the value of objects. We can use the equals() method of the String class, which checks whether the value of two objects are equal to one another. The format of an equals() method call is as follows...

     object1.equals(object2)

In the Grades class, we can simply change the "==" operator to a .equals(), and put the "A" into the parameters...

Now the condition evaluates whether letterGrade has a value of "A", and will therefore return true, setting the gradePointValue for hist to 4.0. 





compareTo()

The compareTo() String method compares Strings lexicographically, or in dictionary order. It will return 0 if the Strings are the same string, a negative number if the left value comes sooner in alphabetical order, and a positive number if the left value comes later.


Output


The trim() method

The trim() method returns all the leading ( before the chars ) and trailing ( after the chars ) whitespace from a character String.




toUpperCase and toLowerCase




The toUpperCase() method returns a String with the same letters as the original, but with all uppercase letters.


The toLowerCase() method returns a String with the same letters as the original, but replaces any uppercase letters with lowercase.







replaceAll()

The replaceAll() method takes two parameters. It returns a new String from the original, replacing all characters that match the first parameter with the second parameter.


------------------------------------------------------------------------------------------------------------------------

APLab_11


Please download the lab files here