2017-12-03 2 views
-2

So produzieren ive meine Textdatei bekam die so getrennt wird:versucht, ein String-Array zu einem Doppel zu konvertieren und zu einem Gesamtpreis

Titel - Autor - Preis - Verlag - ISBN (es muss wie sein this)

und was ich will zu tun ist, alle Preis Werte aus diesem Textdokument erhalten:

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 - Kurs Tech - 1439055661

802,11 Sicherheit - Jon Edney und 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

Dieser Code ist, was ich bisher habe, aber ich bin wirklich stecken als wie man die Gesamtwerte vom splitArray [2] erhält, das ein String-Typ ist.

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

Alle Daten in der Datei wird geteilt und dann in die verschiedenen Arrays gesetzt wird, die alle String-Typen sind, aber dies ist ein Problem, da ich den Gesamtpreis der alle Bücher zu finden versuche.

Jede Hilfe zu diesem Problem geschätzt würde, habe ich mehr Möglichkeiten ausprobiert, aber ich scheine immer wieder einen Nullwert zu erhalten oder 0,0

+0

Parse die Zeichenfolgen zu Zahlen vielleicht? –

+1

Mögliches Duplikat von [Zeichenfolge in Java doppelt konvertieren] (https://stackoverflow.com/questions/5769669/convert-string-to-double-in-java) –

+0

Das war nicht der richtige Weg, um Ihren Beitrag zu entfernen. Zerstöre es nicht noch einmal. – Andy

Antwort

0

In diesem Beispiel habe ich gezeigt, wie eine Summe von Double-Werten von String zu machen Array. Es könnte in Ihrem Beispiel hilfreich sein:

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

Ich denke, das größte Problem Ihre Vermutung ist, dass es 4 Elemente in der Fünf-Elemente-Linie sein. if(splitArray.length == 4) ist falsch. Ich würde auch bevorzugen, einen regulären Ausdruck split zu verwenden, der den Leerraum im Trennzeichen verbrauchte. Außerdem hatten Sie viele anonyme und verschachtelte Blöcke. Ich würde alle Preise in einem List speichern und dann (angenommen Java 8+) Ströme verwenden, um das DoubleSummaryStatistics am Ende zu bestimmen. Etwas wie,

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"); 
Verwandte Themen