How do I store the result into objects and calculate them? Program: import java.
ID: 3876766 • Letter: H
Question
How do I store the result into objects and calculate them?
Program:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Fraction {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("F://anand/Chegg/src/fraction.txt");//opening a file using file reader
BufferedReader br=new BufferedReader(fr);//creating buffered reader object to read data from file
String str;//to hold each line read from file
while((str=br.readLine())!=null)//reading each line untill end of file
{
String st[]=str.split(" ");//splitting with space in this input file there is no space netween sign and number
if(!st[1].equals("0"))//cheking whwther denominator is equals to zero or not if not displaying thefraction
System.out.println("Fraction is : "+st[0]+"/"+st[1]);
}
}
}
Explanation / Answer
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Fraction {
double n;//to store numerator
double d;//to store denominator....
Fraction(double s, double q)
{
this.n =s;
this.d = q;
}
public static void main(String[] args) throws IOException
{
//all fractions are stored in arraylist
ArrayList<Fraction> l = new ArrayList<Fraction>();
FileReader fr=new FileReader("F://anand/Chegg/src/fraction.txt");//opening a file using file reader
BufferedReader br=new BufferedReader(fr);//creating buffered reader object to read data from file
String str;//to hold each line read from file
while((str=br.readLine())!=null)//reading each line untill end of file
{
String st[]=str.split(" ");//splitting with space in this input file there is no space netween sign and number
if(!st[1].equals("0"))//cheking whwther denominator is equals to zero or not if not displaying thefraction
System.out.println("Fraction is : "+st[0]+"/"+st[1]);//here after printing fractions
//adding them to arraylist...
//to calculate or what ever you want
l.add(new Fraction(Double.parseDouble(st[0]),Double.parseDouble(st[1])));//passing fractions by convertin them to double....
//now all the fractions are present in arraylist....l
//you can use them
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.