How do I achieve the following results using the P

2020-05-01 07:11发布

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: mixed.txt

2条回答
Lonely孤独者°
2楼-- · 2020-05-01 07:22

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

查看更多
地球回转人心会变
3楼-- · 2020-05-01 07:23

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

查看更多
登录 后发表回答