我的应用程序提示用户输入一个文本文件,mixed.txt,其中包含
12.2 安德鲁
22 西蒙
苏菲33.33
10 弗雷德
21.21 汉克
坎迪斯12.2222
接下来,应用程序将PrintWrite
写入所有文本文件,即result.txt和errorlog.txt。 mix.txt 中的每一行都应以数字开头,后跟名称。然而,某些行可能包含相反的意思,即先说名称,然后再跟一个数字。以数字开头的行应添加到 sum 变量并写入 result.txt 文件,而以名称和数字开头的行应写入 errorlog.txt 文件。
因此,在MS-DOS控制台上的结果如下:
type result.txt
总计:65.41
type errorlog.txt
第 3 行出错 - Sophie 33.33
第 6 行错误 - Candice 12.2222
好的,这是我的问题。我只设法到达将所有数字添加到 result.txt 并将名称添加到 errorlog.txt 文件的阶段,我不知道如何从那里继续。那么你们能给我一些关于如何实现我需要的结果的建议或帮助吗?
下面是我的代码:
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();
}
}
这是mixed.txt文件的屏幕截图:
最佳答案
您可以像这样更改 while 循环:
int lineNumber = 1;
while (fileInput.hasNextLine()) {
String line = fileInput.nextLine();
String[] data = line.split(" ");
try {
sum+= Double.valueOf(data[0]);
} catch (Exception ex) {
output2.println("Error at line "+lineNumber+ " - "+line);
}
lineNumber++;
}
output.println("Total: "+sum);
在这里,您可以浏览 mixed.txt
的每一行并检查它是否以 double 开头。如果它是 double 的,您可以将其添加到 sum
中,否则您可以将字符串添加到 errorlog.txt 中。最后您可以将总和添加到 result.txt
关于java - 如何使用文本文件中的 PrinterWriter 类获得以下结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25485260/