如何使用文本文件中的PrinterWriter类实现以下结果?

我的应用程序在此处提示用户输入包含的文本文件mixed.txt

12.2 Andrew 22 Simon Sophie 33.33 10 Fred 21.21 Hank Candice 12.2222

接下来,应用程序是PrintWrite到所有文本文件,即result.txterrorlog.txt 。 mixed.txt中的每一行都应以数字开头,后跟名称。 但是,某些行可能包含另一种方式来表示名称,然后是数字。 以数字开头的那些应加到sum变量并写入result.txt文件,而那些以名称开头的行和数字应写入errorlog.txt文件。

因此,在MS-DOS控制台上的结果如下:

输入result.txt

总计:65.41

输入errorlog.txt

第3行出错 – 索菲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文件的屏幕截图: 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 ,否则你可以将String添加到errorlog.txt。 最后,您可以将总和添加到result.txt

你应该积累结果,并在循环写入求和之后,你也可以使用普通计数器变量来计算错误行。 例如:

 double mSums =0d; int lineCount = 1; while (fileInput.hasNext()) { String line = fileInput.nextLine(); String part1 = line.split(" ")[0]; if ( isNumeric(part1) ) { mSums += Double.valueOf(part1); } else { output2.println("Error at line " + lineCount + " - " + line); } lineCount++; } output.println("Totals: " + mSums); // one way to know if this string is number or not // http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java public static boolean isNumeric(String str) { try { double d = Double.parseDouble(str); } catch(NumberFormatException nfe) { return false; } return true; } 

这将为您提供错误文件中所需的结果:

第3行出错 – 索菲33.33
第6行出错 – Candice 12.2222