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
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.");
}
}
Step by Step Solution
3.48 Rating (141 Votes )
There are 3 Steps involved in it
Step: 1
I modified your code to fix the problems you brought up and include a way to determine which products are both most and least dear import javaioFile i...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started