My application here prompts the user for a text file, mixed.txt which contains
12.2 Andrew
22 Simon
Sophie 33.33
10 Fred
21.21 Hank
Candice 12.2222
Next, the application is to PrintWrite
to all text files namely result.txt and errorlog.txt. Each line from mixed.txt should begin with a number first followed by a name. However, certain lines may contain the other way round meaning to say name then followed by a number. Those which begins with a number shall be added to a sum
variable and written to the result.txt file while those lines which begin with the name along with the number shall be written to the errorlog.txt file.
Therefore, on the MS-DOS console the results are as follow:
type result.txt
Total: 65.41
type errorlog.txt
Error at line 3 - Sophie 33.33
Error at line 6 - Candice 12.2222
Ok here's my problem. I only managed to get up to the stage whereby I have had all numbers added to result.txt and names to errorlog.txt files and I have no idea how to continue from there onwards. So could you guys give me some advice or help on how to achieve the results 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")); //writes all double values to the file
output2 = new PrintWriter(new File("errorlog.txt")); //writes all string values to the file
}
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 the screenshot of the mixed.txt file: