-3

So ive got my text file which is seperated as so:

Title - Author - Price - Publisher - ISBN (it needs to be like this)

and what I want to do is get all of the price values out of this text document:

Windows XP - Graham Winter - 32.50 - O'Reilly - 0471974555

Windows XP Unwired - Wei Meng Lee - 24.95 - O'Reilly - 0596005369

CCDA Exam Guide - Anthony Bruno - 49.95 - Cisco Press - 0735700745

Multimedia Comms - Fred Halsall - 53.99 - Addison Wesley - 0201398184

Guide to Networks - Tamara Dean - 34.50 - Course Tech - 1439055661

802.11 Security - Jon Edney and William Hal - 68.99 - Addison Wesley - 0321136209 Wireless Hacks - Rob Weeks - 29.50 - O'Reilly - 0596101442

Large Scale LANs - Kevin Dooley - 39.00 - O'Reilly - 0596001509

Learning Java - William Lane -12.00 - Wiley - 0811234561

This code is what I have so far but I am really stuck as to how to get the total values from the splitArray[2] which is a string type.

import java.io.File;
import java.util.Scanner;
import java.io.IOException;


public class Part_2 {

    private static int count;

    public static void main(String[] args){

        int D = 0;
        String  line = "";
        int num = 0;
        Scanner keyboard = new Scanner (System.in);
        {
            // Allow the user to enter the name of text file that the data is stored in
            System.out.println("Type in name of the file");
            String fileName = keyboard.nextLine();

            File Fileobject = new File (fileName);
            {
                if (!Fileobject.exists())
                {
                    System.out.println("Error - File does not exist");
                    System.exit(0);
                }

                try {
                    count = 0;
                    if (count < 5)
                    {
                        Scanner fileReader  = new Scanner (Fileobject);

                        System.out.println("\n"+String.format("%-30s",  "Title") +
                                String.format("%-25s", "Author") +
                                String.format("%-25s", "Price") +
                                String.format("%-25s", "Publisher") +
                                String.format("%-25s", "ISBN"));

                        System.out.println(String.format("%-30s", "=====")+
                                String.format("%-25s", "=====")+
                                String.format("%-25s", "=====")+
                                String.format("%-25s", "======")+
                                String.format("%-25s", "===="));

                        while(fileReader.hasNext())
                        {
                            line = fileReader.nextLine();// Read a line of data from text file
                            num = num +1;

                            // The format of each line of data in the text file is as follow: 
                            // Title - Author - Price - Publisher - ISBN
                            // Need to split each line read from file before can process it

                            try {

                                String [] splitArray = line.split("-");

                                // check to make sure there are 4 parts in splitArray 
                                if(splitArray.length == 4)
                                {
                                    // remove spaces
                                    splitArray[0] = splitArray[0].trim();
                                    splitArray[1] = splitArray[1].trim();
                                    splitArray[2] = splitArray[2].trim();
                                    splitArray[3] = splitArray[3].trim();
                                    splitArray[4] = splitArray[4].trim();
                                }

                                if (splitArray[0].isEmpty())
                                {
                                    D++;
                                }

                                if (splitArray[1].isEmpty())
                                {
                                    D++;
                                }


                                if (splitArray[2].isEmpty())
                                {
                                    D++;
                                }


                                if (splitArray[3].isEmpty())
                                {
                                    D++;
                                }


                                if (splitArray[4].isEmpty())
                                {
                                    D++;
                                }


                                System.out.println(String.format(" %-30s", splitArray[0])+
                                        String.format(("%-25s"), splitArray[1])+
                                        String.format(("%-25s"), splitArray[2])+
                                        String.format(("%-25s"), splitArray[3])+
                                        String.format(("%-25s"), splitArray[4]));


                            }
                            catch (Exception e) {
                                    System.out.println("Line delimiter error");
                                    D++;
                            }
                        }
                        System.out.println("");
                        System.out.println("totals");
                        System.out.println("-----------------------------");
                        System.out.println("The total number of books: ");
                        System.out.println("The total costs of books: ");
                        System.out.println("Maximum cost of a book: " );
                        System.out.println("Minimum cost of a book: " );
                        System.out.println("Average cost of a book: " );
                        System.out.println("there are " + D + " error(s) within the text document");
                    }
                }
                catch (IOException e) {
                    // IO error while reading from the file.
                    System.err.println("Error while reading from file ");
                }   
            }
        }
    }
}

All of the data in the file gets split and then is put into the different arrays which are all string types, however this is a problem as I am trying to find the total price of all of the books.

Any help on this problem would be appreciated, I have tried multiple ways but I always seem to get back a null value or 0.0

Toto
  • 89,455
  • 62
  • 89
  • 125
12345
  • 1
  • 2

2 Answers2

0

In this example I have shown how to make a sum of Double values from String array. It might be helpful in your example:

double sum = 0;
String[] strings = "1 2 3 4 5 6".split(" "); // this is just an example, quick way to create array of Strings containing values that can be parsed to Doubles in next step.
for(int i = 0; i < strings.length; i++) {
    Double d = Double.parseDouble(strings[i]);
    sum += d;
}
System.out.println(sum);
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
0

I think the biggest issue is your assumption that there will be 4 elements in your five element line. if(splitArray.length == 4) is incorrect. I would also prefer using a split regular expression that consumed the white space in the separator. Also, you had a lot of anonymous and nested blocks. I would store all of the prices in a List and then use (assuming Java 8+) streams to determine the DoubleSummaryStatistics at the end. Something like,

int D = 0;
Scanner keyboard = new Scanner(System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("Type in name of the file");
String fileName = keyboard.nextLine();

File fileObj = new File(fileName);
if (!fileObj.exists()) {
    System.out.println("Error - File does not exist");
    System.exit(0);
}
List<Double> prices = new ArrayList<>();
try (Scanner fileReader = new Scanner(fileObj)) {
    while (fileReader.hasNextLine()) {
        String line = fileReader.nextLine();
        String[] tokens = line.split("\\s*-\\s*");
        if (tokens.length == 5) {
            try {
                prices.add(Double.valueOf(tokens[2]));
            } catch (NumberFormatException nfe) {
                System.out.println("Invalid price: " + tokens[2]);
                D++;
            }
        } else {
            System.out.println("Invalid number of tokens: " + line);
            D++;
        }
    }
} catch (FileNotFoundException fnfe) {
    System.out.println("Error - could not read file");
    System.exit(0);
}
DoubleSummaryStatistics stats = prices.stream()
        .mapToDouble(Double::doubleValue)
        .summaryStatistics();
System.out.println("");
System.out.println("totals");
System.out.println("-----------------------------");
System.out.println("The total number of books: " + stats.getCount());

System.out.println("The total costs of books: " + stats.getSum());
System.out.println("Maximum cost of a book: " + stats.getMax());
System.out.println("Minimum cost of a book: " + stats.getMin());
System.out.println("Average cost of a book: " + stats.getAverage());
System.out.println("there are " + D + " error(s) within the text document");
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249