Sample Program - Vector of Fractions

//
//  class FractionVector
//
//      main function to demonstrate a Vector of Fractions
//

import java.util.Vector;
import java.util.Enumeration;

class FractionVector {

    public static void main(String[] args) {
    	Vector fraclist = new Vector();

//  create Fractions and add them to the vector

        Fraction first = new Fraction(1,2);
        Fraction second = new Fraction(3,2);
        Fraction third = new Fraction(1,7);
        Fraction fourth;
        Fraction fracout;
    	fraclist.addElement(first);
	fraclist.addElement(second);
    	fraclist.addElement(third);

//  create Enumeration and use it to print all Fractions in the Vector

        System.out.println("\nContents of the Vector:");
	Enumeration allfracs = fraclist.elements();
    	while (allfracs.hasMoreElements()) {
            fracout = (Fraction) allfracs.nextElement();
    	    System.out.println("The next fraction is " + fracout);
	}
//  add another fraction to the Vector

        fourth = first.add(second);
        System.out.println("The sum is: " + fourth);
    	fraclist.insertElementAt(fourth,0);

//  use Enumeration to print all elements again

        System.out.println("\nContents of the Vector:");
	allfracs = fraclist.elements();
    	while (allfracs.hasMoreElements()) {
	    fracout = (Fraction) allfracs.nextElement();
    	    System.out.println("The next fraction is " + fracout);
	}

//  get a Fraction out of the Vector and print it

    	fracout = (Fraction) fraclist.elementAt(1);
	System.out.println("\nThe fraction in position 1 is " + fracout);

//  put a String in the vector

    	fraclist.insertElementAt("String object",3);
	String from = (String) fraclist.elementAt(3);
    	System.out.println("In position 3 we inserted the String: " + from);
    }
}

OUTPUT


C:\cafe1.8\Mine>java FractionVector

Contents of the Vector:
The next fraction is 1/2
The next fraction is 3/2
The next fraction is 1/7
The sum is: 8/4

Contents of the Vector:
The next fraction is 8/4
The next fraction is 1/2
The next fraction is 3/2
The next fraction is 1/7

The fraction in position 1 is 1/2
In position 3 we inserted the String: String object

C:\cafe1.8\Mine>


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page