0

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

Scorpiorian83
  • 469
  • 1
  • 4
  • 17
  • Divide and Conquer. Use `nextLine` to read a line as String. Then go on deciding if that line starts with a number or a name and handle it correspondingly. Then read the next full line ... – Fildor Aug 25 '14 at 12:10
  • According to the screenshot, your input is on one single line. We assumed there were `newLine`s after each dataset. That will make things complicated. Personally, I'd say your Input is broken and useless and urge the creator to create a valid Input file. But I guess the horrible input is the main task to be dealt with in this assignment ... :( – Fildor Aug 26 '14 at 06:50

2 Answers2

3

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

Chaitanya
  • 15,403
  • 35
  • 96
  • 137
  • oh hey hi thanks for viewing this question for me. :D erm i tried to change my while loop to exactly yours but it doesn't work. the total is 0 while all the lines are added to the errorlog text file. Thanks! – Scorpiorian83 Aug 25 '14 at 13:24
  • Oh, I tried this code in my machine and it worked, seems to be I am using different `mixed.txt` contents. – Chaitanya Aug 25 '14 at 15:27
  • oh hey hi I just put in a screenshot of the file hope it helps. :) – Scorpiorian83 Aug 26 '14 at 03:34
  • oh hey hi so your input is in one single line? We assumed there is one line per "entry". That will make things complicated @Scorpiorian83. – Fildor Aug 26 '14 at 06:46
  • @Fildor hi Fildor oh yes so sorry i confused everyone because when I pasted the contents in the text file it showed exactly like the one on top of the question. – Scorpiorian83 Aug 26 '14 at 06:50
  • So the original Input is with or without newlines? That's important. If it hasn't got any newlines, we cannot separate entries with `nextLine` @Scorpiorian83 – Fildor Aug 26 '14 at 06:57
  • @Fildor erm I tried before printing to console with the `nextLine()` and they seems to be newline entries though. – Scorpiorian83 Aug 26 '14 at 07:00
  • @Scorpiorian83 ok, then they got lost somehow while copying to the Textfile for screenshot. Then the answer is still valid. – Fildor Aug 26 '14 at 07:03
  • @Fildor yeah the `nextLine()` printed to console is `12.2 Andrew` but when I try to print `Double.valueOf(data[0])` it says there is a numberformat exception. – Scorpiorian83 Aug 27 '14 at 07:04
  • @user2065083 oh hey mate i just managed to get it working now but can i ask you a question regarding the catch exception code? I've just learnt about exceptions not long so I don't quite understand the purpose of yours? does it mean that for those which does not begin with a number the exception suppose to print to file? Thanks! – Scorpiorian83 Aug 28 '14 at 03:48
  • Yes correct, in try block we are just trying to convert `data[0]` to `double` and add that result to `sum`, but if `data[0]` is not of type `double` then we will get an exception, so we are just writing that complete line to the file pointed by `output2` – Chaitanya Aug 28 '14 at 05:18
1

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

Wajdy Essam
  • 4,280
  • 3
  • 28
  • 33
  • oh hey hi thanks for helping me here can I ask you what is 0d stands for? Thanks! – Scorpiorian83 Aug 25 '14 at 13:25
  • 1
    `0` means value `0` and `d` means decimal. Here `d` is optional. You can refer the Java docs for Floating-Point Literals --> http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html, it says `A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.` – Chaitanya Aug 25 '14 at 15:26
  • welcome, small correction here, `d` represents `Double`, not decimal. – Chaitanya Aug 26 '14 at 05:17