I have this code, I have some issue to fix: 1- I need the code to allow
Question:
I have this code, I have some issue to fix:
1- I need the code to allow me to write in the products.txt file
2-The program is duplicating whatever is writing on products.txt in products_output.txt and I just need it one time
3-From this code I would like to add a sort method that tells me with product is most expensive and cheaper.
//FileExercise.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileExercise
{
public static void main(String[] args)
{
String filename="products.txt";
String out_filename="products_output.txt";
Scanner filereader =null;
PrintWriter writer=null;
String productName="";
String pricestr="";
/*try-catch block*/
try
{
//Open file for reading
filereader =new Scanner(new File(filename));
//Open file for writing
writer =new PrintWriter(new File(out_filename));
while(filereader.hasNextLine())
{
/*Split the data by = sing*/
String data[]=filereader.nextLine().trim().split("=");
//Get data for name of the product
productName=data[0];
//Get data for price of the product
pricestr=data[0];
writer.printf("%s %s\r\n", productName,pricestr);
}
/*close objects of the Scanner and Writer class*/
filereader.close();
writer.close();
System.out.println("Data write to "+out_filename+" file successully.");
}
catch(FileNotFoundException exp)
{
System.out.println(exp.getMessage());
}
catch(Exception exp)
{
System.out.println(exp.getMessage());
}
System.out.println("Closing the program.");
}
}
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill