pep8 program specify a structure called Fraction with num and denom as its integ
ID: 3771359 • Letter: P
Question
pep8 program
specify a structure called Fraction with num and denom as its integer members. Keep asking the user if he or she wants to add a fraction. If the answer is 'y' or 'Y', allocate memory dynamically for a Fraction structure, read a fraction and store the pointer returned by new in a locally defined array of integers of maximum size 10.
Then, read a Fraction, storing it in a Fraction variable local to main and search for it in the above array of pointers. Print the index where it was found or "Not found" otherwise.
The following shows a sample execution of the program:
Input: 2 / 3 1 / 2 1 / 4 1 / 3 2 / 5 -99
Enter fraction to search for: 1/3
1/3 was found at index 3.
Explanation / Answer
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(" Contents 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(" Contents 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(" The 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);
}
}
thank you
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.