Consider the following class: public class Fraction{ private int numerator; priv
ID: 3920769 • Letter: C
Question
Consider the following class: public class Fraction{ private int numerator; private int denominator; private static char slash = ‘/’, } Write a program to instantiate an object of the Fraction class to test the class.. Add a constructor(s), set and get methods to the Fraction class appropriately. Using the Serializable Interface, instantiate and write three Fraction objects to a file called “SerialF.dat.” A loop must be used when creating and writing the three objects to the file. You can select the values you wish to use for the denominator and numerator. Directions • Create the Fraction Class. o Add a constructor(s), set and get methods to the Fraction class appropriately. o Ensure the class is Serializable. • Use a loop to create three Fraction objects. o Initialize the three objects, o Write each object to the file“SerialF.dat.” Display an appropriate message if an exception occurs
Explanation / Answer
import java.io.*;
import java.util.*;
class Fraction implements Serializable{
private int numerator;
private int denominator;
private static char slash = '/';
public Fraction(){
numerator = 0;
denominator = 1;
}
public Fraction(int a, int b){
numerator = a;
denominator = b;
}
public String toString(){
return (Integer.toString(numerator) + slash + Integer.toString(denominator));
}
public void setNumerator(int a){
numerator = a;
}
public void setDenominator(int a){
if (a != 0)
denominator = a;
else
denominator = 1;
}
public int getNumerator(){
return numerator;
}
public int getDenominator(){
return denominator;
}
}
public class Demo246 {
public static void main(String[] args){
Fraction[] list = new Fraction[3];
for (int i = 0; i<3; i++){
list[i] = new Fraction();
list[i].setNumerator(i);
list[i].setDenominator(i+1);
}
try {
FileOutputStream fout = new FileOutputStream("Serial.dat");
ObjectOutputStream oout = new ObjectOutputStream(fout);
for (int i = 0; i<3; i++){
oout.writeObject(list[i]);
}
oout.close();
}
catch(Exception e){
System.out.println("IOException is caught");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.