How do I achieve the following results using the PrinterWriter class from a text file?

荒凉一梦 提交于 2019-12-02 07:31:36

You can change your while loop like this:

    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);

Here you can go through each line of the mixed.txt and check if it starts with a double or not. If it is double you can just add it to sum or else you can add the String to errorlog.txt. Finaly you can add the sum to result.txt

you should accumulate the result and after the loop write the summation, also you can count the lines for error using normal counter variable. for example:

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;  
    }

this will give you the result you want in error files:

Error at line 3 - Sophie 33.33
Error at line 6 - Candice 12.2222

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!