My application here offers the user a mixed.txt text file that contains
12.2 Andrew
22 Simon
Sophie 33.33
10 Fred
21.21 Hank
Candice 12.2222
Next, the application will be PrintWriteto all text files, namely result.txt and errorlog.txt . Each line in the mixed.txt file must begin with a number first, followed by a name. However, some lines may contain a different value, meaning a name and then a number. Those starting with a number must be added to the variable sumand written to the result.txt file, while those lines starting with the name along with the number must be written to the errorlog.txt file.
Therefore, on the MS-DOS console, the following results:
enter result.txt
Total: 65.41
enter errorlog.txt
Error on line 3 - Sophie 33.33
Error on line 6 - Candice 12.2222
Ok, here is my problem. I only managed to get on the scene when I had all the numbers added to result.txt and the names in the errorlog.txt files, and I don’t know how to continue from there. Could you guys give me some advice or help on how to achieve the results that I need?
Below will be my code:
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do {
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if (a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch (FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
} while (fileInput == null);
PrintWriter output = null;
PrintWriter output2 = null;
try
{
output = new PrintWriter(new File("result.txt"));
output2 = new PrintWriter(new File("errorlog.txt"));
}
catch (IOException g)
{
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext())
{
if (fileInput.hasNextDouble())
{
double num = fileInput.nextDouble();
String str = Double.toString(num);
output.println(str);
} else
{
output2.println(fileInput.next());
fileInput.next();
}
}
fileInput.close();
output.close();
output2.close();
}
}
This is a screenshot of the mixed.txt file:

source
share