Helpful Information
 
 
Category: Java
Processing multiple files separately

Hi guys,
I am actually a computer science students who is currently facing some doubts in one of my java programming practical exercise.

Here are my doubts:
The aim of this program is to read multiple files and output
1) the amount of numbers in the file
2) the sum of the numbers
3) the amount of negative numbers

I tried the code by selecting one file to be read and it works prefectly but when I try multiple files, the program reads them but the output is merged together instead of seperately.

Here are the codes:
import javax.swing.*;
import java.io.*;
import java.util.*;

public class Writer
{
int totalNumber=0;
int negativeNumber=0;
int totalSum=0;
String text;
JFileChooser fc = new JFileChooser();

public void read()
{
//Enable multiple file selection
fc.setMultiSelectionEnabled(true);
int option = fc.showOpenDialog(null);
if(option==JFileChooser.APPROVE_OPTION)
{
File[] listOfFiles = fc.getSelectedFiles();
for(int i=0;i<listOfFiles.length;i++)
{
File f = listOfFiles[i];
//}
// }
// {
try
{
File f1 = fc.getSelectedFile();
FileReader fr = new FileReader(f1);
BufferedReader in = new BufferedReader(fr);
while(true)
{
String s =in.readLine();
Scanner sc = new Scanner(s);
double number = sc.nextDouble();
if(number<0)
{
negativeNumber++;
}
totalNumber++;
totalSum += number;
if (s==null) break;
}
in.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
}

public void write()
{
//Write the results to a file
try
{
File[] listOfFiles = fc.getSelectedFiles();
for(int i=0;i<listOfFiles.length;i++)
{
String text = listOfFiles[i].getPath();
FileWriter fw = new FileWriter(text+".out");
PrintWriter out = new PrintWriter(fw);
String numbers = "Amount of numbers:" + totalNumber;
System.out.println(numbers);
String sum = "Sum of the numbers:" + totalSum;
System.out.println(sum);
String negative = "Amount of negative numbers:" + negativeNumber;
System.out.println(negative);
out.println(numbers);
out.println(sum);
out.println(negative);
out.close();
totalNumber=0; //reset the counter
negativeNumber=0; //reset the counter
totalSum=0; // reset the counter
}

}
catch (Exception ex)
{
System.out.println(ex);
}
}
}










privacy (GDPR)