MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

Embed Size (px)

Citation preview

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    1/32

    MELJUNCORTES,MBA,MPA,BSCS,ACS

    class Rectangle{

    private double width = 10.0;private double length = 15.0;

    public Rectangle(){

    // do nothing, defaults are fine}

    public Rectangle(double width, double length){

    this.width = width; OUTPUT:this.length = length;

    }

    // create square given just one sidepublic Rectangle(double side)

    {length = width = side;

    }

    public double getWidth() { return width; }public double getLength() { return length; }public double getPerim() { return 2 * width + 2 * length; }public double getArea() { return width * length; }

    }

    class RectangleTester{

    // the tester programpublic static void main(String[] args){

    Rectangle r1 = new Rectangle();System.out.println("r1: " + r1.getWidth() + " x " + r1.getLength() +

    " Perim: " + r1.getPerim() + " Area: " + r1.getArea() );

    Rectangle r2 = new Rectangle(20.0, 40.0);System.out.println("r2: " + r2.getWidth() + " x " + r2.getLength() +" Perim: " + r2.getPerim() + " Area: " + r2.getArea());

    Rectangle r3 = new Rectangle(10.0); // pass in one sideSystem.out.println("r3: " + r3.getWidth() + " x " + r3.getLength() +

    " Perim: " + r3.getPerim() + " Area: " + r3.getArea());

    }

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    2/32

    MELJUNCORTES,MBA,MPA,BSCS,ACS

    import java.text.NumberFormat;

    class Employee{

    private String name;

    private double salary;

    OUTPUT:// constructor initializes the memberspublic Employee(String name, double salary){

    this.name = name;this.salary = salary;

    }

    // overloaded - takes one double

    public double getBonus(double percent){

    return salary * percent;}

    // overloaded - takes two doublepublic double getBonus(double percent, double additional){

    return salary * percent + additional;}

    // overloaded - takes three doublespublic double getBonus(

    double percent,double additional,double max)

    {double bonus = salary * percent + additional;return bonus min) )

    {return bonus;

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    3/32

    MELJelse // out of range, return max or min{ return bonus > max ? max : min;}}

    }

    class EmployeeBonusOverloadedMethod{

    // the tester programpublic static void main(String[] args){

    Employee emp1 = new Employee("John", 50000);double bonus = emp1.getBonus(.5);NumberFormat formatter = NumberFormat.getCurrencyInstance();String bonusString = formatter.format(bonus);

    System.out.println("John's bonus:\t" + bonusString);

    Employee emp2 = new Employee("Paul", 75000);bonus = emp2.getBonus(.25, 10000);bonusString = formatter.format(bonus);System.out.println("Paul's bonus:\t" + bonusString);

    Employee emp3 = new Employee("George", 100000);bonus = emp3.getBonus(.50, 25000, 60000);bonusString = formatter.format(bonus);System.out.println("George's bonus:\t" + bonusString);

    Employee emp4 = new Employee("Ringo", 20000);bonus = emp4.getBonus(.20, 5000, 60000, 10000);bonusString = formatter.format(bonus);System.out.println("Ringo's bonus:\t" + bonusString);

    }}

    OUTPUT:

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    4/32

    MELJclass Employee{ private String name;private double salary;// constructor initializes the memberspublic Employee(String name, double salary)

    {this.name = name; OUTPUT:this.salary = salary;

    }

    public double getBonus(double percent){

    return salary * percent;}

    }

    class EmployeeBonus{

    // the tester programpublic static void main(String[] args){

    Employee emp = new Employee("Joe", 50000);double bonus = emp.getBonus(.5);

    System.out.println("Joe's bonus: $" + bonus);}

    }

    OUTPUT:

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    5/32

    MELJclass SimpleArray{ public static void main(String[] args){ SimpleArray s = new SimpleArray();s.run();

    } OUTPUT:

    public void run(){

    // an array of 10 integersint[] array1 = new int[10];

    // directly fill the arrayarray1[0] = 2;array1[1] = 4;array1[2] = 6;array1[3] = 8;

    array1[4] = 10;array1[5] = 12;array1[6] = 14;array1[7] = 16;array1[8] = 18;array1[9] = 20;

    // display the contentsSystem.out.println("First time:");for ( int i = 0; i < 10; i++ ){

    System.out.println(i + ": " + array1[i]);}

    // reuse the array referencearray1 = new int[10];

    // fill the array in a for loopfor ( int i = 0; i < 10; i++ ){

    array1[i] = i * 3;

    }

    // display the contentsSystem.out.println("\nSecond time:");for ( int i = 0; i < 10; i++ ){

    System.out.println(i + ": " + array1 [i]);} // end for

    } // end run} // end class

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    6/32

    MELJclass SimpleArrayInitialization{ public static void main(String[] args){ SimpleArrayInitialization s = new SimpleArrayInitialization();s.run();

    }

    public void run(){

    // an array of 10 integersint[] array1 = {2,4,6,8,10,12,14,16,18,20};

    // display the contentsSystem.out.println("array1:");for ( int i = 0; i < 10; i++ ){

    System.out.println(i + ": " + array1[i]);}

    } // end run} // end class

    OUTPUT:

    class SumOfDice{

    int[] diceValues = new int[13];

    public static void main(String[] args){

    SumOfDice d = new SumOfDice();d.run();

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    7/32

    MELJprivate void run()

    {System.out.print("Rolling...");

    // roll the die one million timesfor ( int i = 0; i < 1000000; i++ ) OUTPUT:

    {// print a dot every 100,000 timesif ( i % 100000 == 0 ){

    System.out.print(".");}

    int die1 = rollDie();int die2 = rollDie();

    diceValues[die1 + die2]++;

    }

    display();}

    private void display(){

    System.out.print("\n\n");

    // tick through the arrayfor ( int i = 2; i

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    8/32

    MELJ// place at top of fileimport java.text.NumberFormat;class SumOfDiceHistogram{ int[] diceValues = new int[13];public static void main(String[] args){

    SumOfDiceHistogram d = new SumOfDiceHistogram();d.run();

    }

    private void run(){

    System.out.print("Rolling...");

    // roll the die one million times

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

    // print a dot every 100,000 timesif ( i % 100000 == 0 ){

    System.out.print("."); OUTPUT:}

    int die1 = rollDie();int die2 = rollDie();

    diceValues[die1 + die2]++;}

    display();}

    public void display(){System.out.print("\n\n");

    // tick through the arrayfor ( int i = 2; i

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    9/32

    MELJ// display the total foundNumberFormat formatter = NumberFormat.getNumberInstance();String totalFound = formatter.format(diceValues[i]);System.out.println(" [" + totalFound + "]");

    }

    }

    private int rollDie(){

    // 0

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    10/32

    MELJimport java.text.NumberFormat;// Histogram - a bar chart representing a// frequency distributionclass Histogram{

    // allows you to track numbers from low to high// rather than from zero offsetprivate int lowOffset;private int highOffset;

    // hold the results in an arrayprivate int[] theArray;

    // constructor takes low and high, creates// array and stores low and high valuespublic Histogram(int low, int high)

    {lowOffset = low; // arrays count from zerohighOffset = high;theArray = new int[high - low + 1]; // size the array

    }

    // given an index, increment the value at the// appropriate offsetpublic void increment(int index){

    int adjustedIndex = index - lowOffset;theArray[adjustedIndex]++;

    }

    // scale the values by division// if scale = 1,000 show every 1,000th as *public void display(int scale){

    System.out.print("\n\n");

    // tick through the array

    for ( int i = 0; i < highOffset - lowOffset + 1; i++ ){int scaledValue = theArray[i] / scale;

    int adjustedOffset = i + lowOffset;System.out.print(adjustedOffset + ":\t");for ( int j = 0; j < scaledValue; j++ ){ OUTPUT:

    System.out.print("*");}

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    11/32

    MELJ// display the total foundNumberFormat formatter = NumberFormat.getNumberInstance();String totalFound = formatter.format(theArray[i]);System.out.println(" [" + totalFound + "]");}

    }}

    class HistogramTwoDie{

    public static void main(String[] args){

    HistogramTwoDie h = new HistogramTwoDie();h.run();

    }

    public void run(){

    // create a histogram to hold// the values of two diceHistogram histogram = new Histogram(2,12);System.out.print("Rolling...");

    // roll the dice one million timesfor ( int i = 0; i < 1000000; i++ ){

    // print a dot every 100,000 timesif ( i % 100000 == 0 ){

    System.out.print(".");}int firstDie = rollDie();int secondDie = rollDie();histogram.increment(firstDie + secondDie);

    }// print with one * = 5,000

    histogram.display(5000);

    }

    private int rollDie()

    {

    // 0

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    12/32

    MELJclass DoubleInts{ public static void main(String[] args) OUTPUT:{ DoubleInts d = new DoubleInts();d.run();

    }

    // Double an integer.// Beware of pass by value!private void doubler(int theInt){

    System.out.println("doubler was: " + theInt);theInt *= 2;System.out.println("doubler now: " + theInt);

    }

    public void run()

    {int x = 15;System.out.println("run before doubler: " + x);doubler(x);System.out.println("run after doubler: " + x );

    } // end run} // end class

    class Employee

    { public int age; OUTPUT:public String name;

    public Employee(String name, int age){

    this.name = name;this.age = age;

    }

    public String toString()

    {return (name + "(" + age + ")");

    }}

    class ByReference{

    private void modify(Employee theEmployee){

    System.out.println("modify received: " + theEmployee);theEmployee.age /= 2; //cut age in half

    theEmployee.name = "New Name";System.out.println("after modification: " + theEmployee);

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    13/32

    MELJpublic void run(){ Employee joe = new Employee("Joe", 45);System.out.println("run before modifcation: " + joe);modify(joe);System.out.println("run after modification: " + joe);

    }

    public static void main(String[] args){

    ByReference b = new ByReference();b.run();

    }}

    class DoubleArray{

    public static void main(String[] args){

    DoubleArray d = new DoubleArray();d.run();

    }

    private void doubler(int[] theArray){

    System.out.println("\ndoubler received this array:");for ( int i = 0; i < theArray.length; i++ )

    { System.out.print(theArray[i] + " ");}

    for ( int i = 0; i < theArray.length; i++ ){

    theArray[i] *= 2;}

    System.out.println("\ndoubler modified the array to: ");for ( int i = 0; i < theArray.length; i++ )

    {System.out.print(theArray[i] + " ");

    } OUTPUT:}

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    14/32

    MELJpublic void run(){ int[] intArray = {1,3,5,7,9,11,13,15};System.out.println("\nthe array in run:");for ( int i = 0; i < intArray.length; i++ )

    {System.out.print(intArray[i] + " ");

    }

    doubler(intArray);

    System.out.println("\nthe array back in run:");for ( int i = 0; i < intArray.length; i++ ){

    System.out.print(intArray[i] + " ");}

    System.out.println();} // end run

    } // end class

    class DoubleArray2{

    public static void main(String[] args){

    DoubleArray2 d = new DoubleArray2();d.run();

    }

    // Double an integer.// Beware of pass by value!private void doubleAnInt(int theInt){

    System.out.println("doubleAnInt received: " + theInt);theInt *= 2;System.out.println("doubleAnInt modified to: " + theInt);

    } OUTPUT:

    public void run(){

    int[] intArray = {1,3,5,7,9,11,13,15};

    // extract a single member from the array and// pass that to the doubleAnInt method

    for ( int i = 0; i < intArray.length; i++ ){

    doubleAnInt(intArray[i]);}

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    15/32

    MELJSystem.out.println("\nthe array back in run after calling doubleAnInt");for ( int i = 0; i < intArray.length; i++ ){System.out.print(intArray[i] + " ");

    }

    System.out.println("");} // end run

    } // end class

    OUTPUT:

    import java.text.NumberFormat;

    class DieArray2D{

    // constant for how many times to// iterate over the experimentstatic final int ITERATIONS = 10;

    // two-dimensional array to hold rolls of the dice// rows = each experiment// columns = each total (e.g., 2-12)int[][] diceValues = new int[ITERATIONS][13];

    public static void main(String[] args){

    DieArray2D d = new DieArray2D();d.run();

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    16/32

    MELJpublic void run(){ System.out.print("Rolling...");// outer loop - once for each iterationfor ( int iteration = 0; iteration < ITERATIONS; iteration++ )

    {System.out.print("\nIteration: " + iteration + "...");

    // roll the die one million timesfor ( int i = 0; i < 1000000; i++ ){

    // print a dot every 100,000 timesif ( i % 100000 == 0 ){

    System.out.print(".");}

    int firstRoll = rollDie();int secondRoll = rollDie();

    diceValues[iteration][firstRoll + secondRoll]++;}

    }

    display();}

    public void display()

    {// outer loop - once for each iterationfor ( int iteration = 0; iteration < ITERATIONS; iteration++ ){

    System.out.print("\n");

    // tick through the array// and display the totals foundfor ( int i = 2; i

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    17/32

    MELJOUTPUT:

    import java.text.NumberFormat;

    class DieArray2DWithTotals{

    static final int ITERATIONS = 10;

    static final int LOW = 0;static final int HIGH = 1;

    int[][] diceValues = new int[ITERATIONS][13];int[][] totals = new int[13][2];

    public static void main(String[] args){

    DieArray2DWithTotals d = new DieArray2DWithTotals();d.run();

    }

    public void run(){

    System.out.print("Rolling...");

    // outer loop - once for each iterationfor ( int iteration = 0; iteration < ITERATIONS; iteration++ ){

    System.out.print("\nIteration: " + iteration + "...");

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    18/32

    MELJ// roll the die one million timesfor ( int i = 0; i < 1000000; i++ ){ // print a dot every 100,000 timesif ( i % 100000 == 0 ){

    System.out.print(".");

    }

    int firstRoll = rollDie();int secondRoll = rollDie();

    diceValues[iteration][firstRoll + secondRoll]++;}

    }

    display();

    }

    public void display(){

    // outer loop - once for each iterationfor (int iteration = 0; iteration < ITERATIONS; iteration++){

    System.out.print("\n");// tick through the arrayfor ( int i = 2; i currentValue || currentLowest == 0 ){

    totals[i][LOW] = currentValue;}

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    19/32

    MELJ/*totals[i][LOW] =(totals[i][LOW] > diceValues[iteration][i] ||totals[i][LOW] == 0) ?

    diceValues[iteration][i] :

    totals[i][LOW];OUTPUT:

    */}

    }System.out.print("\n\n");

    for ( int j = 0; j < 2; j++ ){

    System.out.print("\n");// tick through the arrayfor ( int i = 2; i

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    20/32

    MELJimport java.lang.*;// one row for the cellular automaton OUTPUT:class CARow{

    // how many cells in a row

    private int rowLength;

    // each cell is either alive (true)// or dead (false)private boolean[] rowData;

    // the rules as an array of// boolean valuesprivate boolean[] rules;

    // public constructor takes the length

    // of the rowpublic CARow(int rowlen){

    rowLength = rowlen;rowData = new boolean[rowLength];rules = new boolean[8];

    }

    // Private constructor called only by// generation(). Makes a cloned row.private CARow(int rowlen, boolean[] theRules){

    rowLength = rowlen;rowData = new boolean[rowLength];rules = theRules;

    }

    // fill the row at randomvoid randomize(){

    for ( int i = 0; i < rowLength; ++i )

    { // the result of a conditional is a boolean, so we just assign itrowData[i] = (java.lang.Math.random() > 0.5);

    }}

    void setCell(int index, boolean value){

    rowData[index] = value;}

    boolean getCell(int index){

    return rowData[index];}

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    21/32

    MELJ// The string should have some subset of the digits 0-7 in it.// Other characters can be present too, if you like,// but they will be ignored.void setRules(String s){

    for ( int i = 0; i < 8; ++i )

    {// If the character corresponding to the number is in the// string, we set its rule, else we delete its rule.int c = '0' + i;int indexFound = s.indexOf(c);boolean wasFound = indexFound != -1;rules[i] = wasFound;

    }}

    // this takes 3 cell indexes and returns the state of

    // the next generation for the center cellprivate boolean nextState(int left, int center, int right){

    // First, calculate a number from 0-7 corresponding to the three cells// read as a boolean value.// If the cells are true false false, this will return 4.int leftVal = rowData[left] ? 4 : 0;int centerVal = rowData[center] ? 2 : 0;int rightVal = rowData[right] ? 1 : 0;

    // this is used as an index into the rule arrayint currentState = leftVal + centerVal + rightVal;return rules[currentState];

    }

    // this processes the current row according to the current rules// and returns another row with the next generation and the same rulespublic CARow generation(){

    // get a rowCARow newRow = new CARow(rowLength, rules);

    // and now all the middle ones are easyfor ( int i = 1; i < rowLength - 1; ++i ){

    boolean newState = nextState(i-1, i, i+1);newRow.setCell(i,newState );

    }// set the two end cellsnewRow.setCell(0, nextState(rowLength-1, 0, 1));newRow.setCell(rowLength-1, nextState(rowLength-2, rowLength-1, 0));

    return newRow;

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    22/32

    MELJ// this gives us the nice ability to print these things easily as stringspublic String toString(){ // string buffers are fasterStringBuffer sb = new StringBuffer(rowLength);for ( int i = 0; i < rowLength; ++i )

    {sb.append(rowData[i] ? '*' : ' ');

    }return new String(sb);

    } OUTPUT:}

    public class OneDimensionalCA{

    // how many columns in our CApublic final static int NCOLS = 32;

    // how many rows in our displaypublic final static int NROWS = 16;

    public static void main(String[] args){

    CARow row = new CARow(NCOLS);

    if ( args.length >= 1 ){

    row.setRules(args[0]);row.randomize();

    }else{

    // if no args are specified, do something pretty// (namely, the Sierpinski's triangle fractal)row.setRules("2345");row.setCell(16, true);

    }

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

    System.out.println(row);row = row.generation();

    }}

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    23/32

    MELJimport java.util.*;class Dog{ OUTPUT:public String name;public int howNoisy;

    public Dog(String name, int howNoisy){

    this.name = name;this.howNoisy = howNoisy < 5 ? howNoisy : 5;

    }

    public void bark(){

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

    System.out.print("Bark ");}

    }}

    class Employee{

    public String name;public double salary;

    // constructor initializes the memberspublic Employee(String name, double salary){ OUTPUT:

    this.name = name;this.salary = salary;

    }}

    class ObjectArrayList{

    public void run(){

    ArrayList myList = new ArrayList();

    // fill the ArrayList with Dogsfor ( int i = 0; i < 10; i++ ){

    String name = "Dog";name += i;myList.add(new Dog(name, i));

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    24/32

    MELJOUTPUT:// display the Dogs and ask them to bark()System.out.print("\nFirst contents of myList...");for ( int i = 0; i < 10; i++ ){

    Dog theDog = (Dog) myList.get(i);

    System.out.print("\n" + theDog.name +". Barks " + theDog.howNoisy + " times: ");

    theDog.bark();}

    // clear the Dogs out of the ArrayListmyList.clear();

    // fill the same ArrayList with Employee objectsfor ( int i = 0; i < 1000; i++ )

    {String name = "Employee";name += i;myList.add(new Employee(name, i*10000));

    }

    // display the EmployeesSystem.out.println("\n\nSecond contents of myList...");for ( int i = 0; i < 1000; i++ ){

    System.out.println("Employee: " + ((Employee)myList.get(i)).name+ ". Salary: " + ((Employee)myList.get(i)).salary);

    }} OUTPUT:

    // the tester programpublic static void main(String[] args){

    ObjectArrayList oa = new ObjectArrayList();oa.run();

    }

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    25/32

    MELJOUTPUT:

    import java.util.*;

    class Dog{

    public String name;public int howNoisy;

    public Dog(String name, int howNoisy){

    this.name = name;this.howNoisy = howNoisy < 5 ? howNoisy : 5;

    }

    *************************************************************************

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    26/32

    MELJimport java.util.*;class Dog{ public String name;public int howNoisy;

    public Dog(String name, int howNoisy){

    this.name = name;this.howNoisy = howNoisy < 5 ? howNoisy : 5;

    } OUTPUT:

    public void bark(){

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

    System.out.print("Bark ");

    }}

    public String toString(){

    return "the dog " + name;}

    }

    class Employee{

    public String name;public double salary;

    // constructor initializes the memberspublic Employee(String name, double salary){

    this.name = name;this.salary = salary;

    }

    public String toString(){return "the Employee " + name;

    }}

    class HeterogeneousArrayList{

    // the tester programpublic static void main(String[] args)

    {HeterogeneousArrayList h = new HeterogeneousArrayList();h.run();

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    27/32

    MELJpublic void run(){ ArrayList myList = new ArrayList();// fill the ArrayList with Dogs

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

    String name = "Dog";name += i;myList.add(new Dog(name, i));

    }

    System.out.println("After adding dogs, " +"myList.size(): " + myList.size());

    // fill the same array with Employee objects

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

    String name = "Employee";name += i;myList.add(new Employee(name, i * 10000));

    }

    System.out.println("After adding Employees, " +"myList.size(): " + myList.size());

    for ( int i = 0; i < myList.size(); i++ ){

    Object o = myList.get(i);

    System.out.println(o.toString() + " ");

    // test if it is a Dog, if so, cast and barkif ( o instanceof Dog ){

    Dog theDog = (Dog) o;System.out.println(theDog.name +

    ". Barks " + theDog.howNoisy + " times.");

    }

    // test if it is an employee, if so cast and check salaryif ( o instanceof Employee ){

    System.out.println("Employee: " +((Employee)myList.get(i)).name+ ". Salary: " + ((Employee)myList.get(i)).salary);

    }

    }

    }}

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    28/32

    MELJOUTPUT:

    import java.util.*; OUTPUT:

    class Employee{

    public String name;public double salary;

    // constructor initializes the memberspublic Employee(String name, double salary){

    this.name = name;this.salary = salary;

    }}

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    29/32

    MELJclass InsertInMidArrayList{ // the tester programpublic static void main(String[] args)

    {InsertInMidArrayList iim = new InsertInMidArrayList();iim.run();

    }

    public void run(){

    ArrayList myList = new ArrayList();

    // insert Employee objects into the center of the ArrayListfor ( int i = 0; i < 5; i++ )

    {String name = "Employee";name += i;myList.add(new Employee(name, i * 100));

    }

    // display the listfor ( int i = 0; i < myList.size(); i++ ){

    System.out.println("Employee: " +((Employee)myList.get(i)).name+ ". Salary: " + ((Employee)myList.get(i)).salary);

    }

    // insert an Employee at offset 3System.out.println("\nInserting employee at offset 3");myList.add(3,new Employee("EmployeeInTheMiddle", 7));

    // re-display the listfor ( int i = 0; i < myList.size(); i++ ){

    System.out.println("Employee: " +((Employee)myList.get(i)).name+ ". Salary: " + ((Employee)myList.get(i)).salary);

    } OUTPUT:}

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    30/32

    MELJimport java.util.*;class Employee OUTPUT:{public String name;public double salary;

    // constructor initializes the memberspublic Employee (String name, double salary){

    this.name = name;this.salary = salary;

    }}

    class Dog{

    public String name;public int howNoisy;

    public Dog(String name, int howNoisy){

    this.name = name;this.howNoisy = howNoisy < 5 ? howNoisy : 5;

    }

    public void bark(){

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

    System.out.print("Bark ");}

    }

    public String toString(){

    return this.name;}

    }

    class SetAndRemoveInArrayList{

    // the tester programpublic static void main(String[] args){

    SetAndRemoveInArrayList a = new SetAndRemoveInArrayList();a.run();

    }

    public void run()

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    31/32

    MELJUN CO{ ArrayList myList = new ArrayList();// fill the array with Employee objectsfor ( int i = 0; i < 10; i++ ){

    String name = "Employee";

    name += i;myList.add(new Employee(name, i * 10000));

    }

    // add a Dog object to the ArrayListmyList.add(5, new Dog("Spot", 4));

    // size the arrayint size = myList.size();

    System.out.println("myList is now " + size + " elements long.");

    for ( int i = 0; i < myList.size(); i++ ){

    Object o = myList.get(i);if ( o instanceof Employee ){

    System.out.println("Employee: " +((Employee)myList.get(i)).name + ". Salary: "+ ((Employee)myList.get(i)).salary);

    }else if ( o instanceof Dog ){

    Dog theDog = (Dog) o;System.out.println("Dog: " + theDog);theDog.bark();System.out.println("\nHey! Who let this dog in here?");System.out.println("Removing dog at index: " + i + "\n");myList.remove(i);System.out.println("Continuing...\n");

    }}

    // find the middle element and replacesize = myList.size();int middle = size / 2;System.out.println("Replacing element " + middle);myList.set(middle, new Employee("New Employee!", 10000));

    System.out.println("\nDisplaying the final contents of myList\n");// show the array with the replaced elementfor ( int i = 0; i < myList.size(); i++ ){System.out.println("Employee: " +

    ((Employee)myList.get(i)).name+ ". Salary: " + ((Employee)myList.get(i)).salary);

    }}

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (SECOND HAND-OUTS)

    32/32