2017-11-04 108 views
0

我是java的初學者,有點卡在這兩個問題中,所以我想 讓程序逐行讀取CSV文件。當讀取java中的CSV文件時NumberFormatException

所以在文件中我有第一行作爲字符串和列是雙。 所以問題是當它讀取第一行它讀取的標題爲雙重,它給了我一個錯誤。

通過它CSV文件

我得到了錯誤的方式是這些低於 異常線程「main」 java.lang.NumberFormatException:對於輸入字符串:「CLOSE」這是第一個錯誤

第二個錯誤>>在sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecima l.java:1222) -

第三個錯誤>>在java.lang.Double.parseDouble(Double.java:510)

福斯錯誤>>>在算法mTrader.ReadInputData(AlgorithmTrader.java:63)

第五錯誤>>在AlgorithmTrader.Run(AlgorithmTrader.java:16)

最後一個錯誤>> SimpleAlgorithmTradingPlatform.main(SimpleAlgorithmTradingPl atform.java:15)

因此,文件的第一行有TIMESTAMP |關閉|高|低|打開|音量和每個行下有數字作爲雙數除了音量有整數

您的建議將不勝感激。由於

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class AlgorithmTrader { 

    public void Run() { 

     ReadInputData(); 
    } 

    public void ReadInputData() { 

     // create object of scanner class for user input 
     Scanner scan = new Scanner(System.in); 
     // declare file name for input file 
     String inputFileName = ""; 

     // input from user for input file 
     System.out.print("Enter Input File Name: "); 
     inputFileName = scan.nextLine(); 
     try { 
      PrintWriter pw = new PrintWriter("output.csv");// to open the file 

      // create a new file 
      File file = new File(inputFileName); 
      // create a new scanner object to read file 
      Scanner readFile = new Scanner(file); 

      // for each line data 
      String line = ""; 

      line = readFile.nextLine();//skip the first line 

      while (readFile.hasNextLine()) { 

       readFile.nextLine(); 
       // pass file to scanner again 
       readFile = new Scanner(file); 

       ArrayList<String> list = new ArrayList<String>(); 

       // read stock data line by line 

       while (readFile.hasNextLine()) { 
        // read line from file 
        line = readFile.nextLine(); 
        // split line data into tokens 
        String result[] = line.split(","); 

        // variables to create a Stock object 

        String timestamp = result[0]; 
        double close = Double.parseDouble(result[1]); 
        double high = Double.parseDouble(result[2]); 
        double low = Double.parseDouble(result[3]); 
        double open = Double.parseDouble(result[4]); 
        int volume = Integer.parseInt(result[5]); 

        // store data into ArrayList 
        list.add(readFile.next()); 
        pw.print(list.add(readFile.next())); 

        Stock stock = new Stock(timestamp, close, high, low, open, volume); 
       }// end of while to read file 

       //close readFile object 
       readFile.close(); 
       pw.close();//close file 
      } 
     } catch (FileNotFoundException e1) { 

      System.out.println(" not found.\n"); 
      System.exit(0); 
     } catch (IOException e2) { 
      System.out.println("File can't be read\n"); 
     } 
    } 
} 

我還有一個文件股票類

而在另一個文件中的主要方法以及

import java.text.DecimalFormat; 

public class SimpleAlgorithmTradingPlatform { 

    public static void main(String[] args) { 

     DecimalFormat fmt = new DecimalFormat("#0.00"); // to get the  DecimalFormat 

     AlgorithmTrader test = new AlgorithmTrader(); 

     test.Run(); 
    } 
} 
+0

請將所有相關信息添加到問題中。沒有評論 – c0der

+0

我已經編輯,希望你明白我想做 感謝 – Abdoh

+0

入住這行代碼:AlgorithmTrader.ReadInputData(AlgorithmTrader.java:63)線63 –

回答

0

這將是很高興看到中的內容,一個虛構的例子您的CSV文件,但請留意我們的任何其他意見。 ;)

它看起來像你的錯誤(可能全部)很可能來自你的股票類。這是另一個發佈的問題,但你的getter和setter需要注意。有些人也錯過了,但也許這是由選擇。

您應該可以用一個掃描儀對象和一個執行此任務,而循環。使用相同的掃描儀對象進行用戶輸入和文件讀取,無論如何都會重新初始化。

下面的代碼是做到這一點的一種方法:

ArrayList<String> list = new ArrayList<>(); 
// create object of scanner class for user input 
// and File Reading. 
Scanner scan = new Scanner(System.in); 
// declare file name for input file 
String inputFileName = ""; 
// input from User for input file name. 
System.out.print("Enter Input File Name: "); 
inputFileName = scan.nextLine(); 

String tableHeader = ""; 
try { 
    // create a new file with PrintWriter in a 
    PrintWriter pw = new PrintWriter("output.csv"); 
    File file = new File(inputFileName); 
    // Does the file to read exist? 
    if (!file.exists()) { 
     System.err.println("File Not Found!\n"); 
     System.exit(0); 
    } 
    // create a new scanner object to read file 
    scan = new Scanner(file); 
    // for each line data 
    String line = ""; 
    tableHeader = scan.nextLine(); 
    String newline = System.getProperty("line.separator"); 
    // Print the Table Header to our new file. 
    pw.print(tableHeader + newline); 

    while (scan.hasNextLine()) { 
     line = scan.nextLine(); 
     // Make sure we don't deal with a blank line. 
     if (line.equals("") || line.isEmpty()) { 
      continue; 
     } 
     // split line data into a String Array. 
     // Not sure if there is a space after 
     // comma delimiter or not but I'm guessing 
     // there is. If not then remove the space. 
     String result[] = line.split(", "); 
     // variables to create a Stock object 
     String timestamp = ""; 
     double close = 0.0; 
     double high = 0.0; 
     double low = 0.0; 
     double open = 0.0; 
     int volume = 0; 

     // Make sure there are enough array elements 
     // from our split string to fullfil all our 
     // variables. Maybe some data is missing. 
     int resLen = result.length; 
     if (resLen > 0) { 
      if (resLen >= 1) { timestamp = result[0]; } 
      if (resLen >= 2) { close = Double.parseDouble(result[1]); } 
      if (resLen >= 3) { high = Double.parseDouble(result[2]); } 
      if (resLen >= 4) { low = Double.parseDouble(result[3]); } 
      if (resLen >= 5) { open = Double.parseDouble(result[4]); } 
      if (resLen >= 6) { volume = Integer.parseInt(result[5]); } 
     } 
     // store data into ArrayList. 
     // Convert the result Array to a decent readable string. 
     String resString = Arrays.toString(result).replace("[", "").replace("]", ""); 
     list.add(resString); 
     // Print the string to our output.csv file. 
     pw.print(resString + System.getProperty("line.separator")); 

     //Stock stock = new Stock(timestamp, close, high, low, open, volume); 
    } 
    //close file 
    scan.close(); 
    pw.close(); 
} 
catch (IOException ex){ 
    System.err.println("Can Not Read File!\n" + ex.getMessage() + "\n"); 
    System.exit(0); 
} 

// Example to show that the ArrayList actually 
// contains something.... 
// Print data to Console Window. 
tableHeader = tableHeader.replace(" | ", "\t"); 
tableHeader = "\n" + tableHeader.substring(0, 10) + "\t" + tableHeader.substring(10); 
System.out.println(tableHeader); 
for (int i = 0; i < list.size(); i++) { 
    System.out.println(list.get(i).replace(", ", "\t")); 
} 
+0

嘿感謝您的幫助我得到了一個錯誤說>>>資源規範不允許在這裏源代碼級別低於1.7 – Abdoh

+0

我更改了代碼以適應您的JDK版本。 – DevilsHnd

3

你是你有NumberFormatException異常,因爲這裏

line = readFile.nextLine();//skip the first line 

不是跳過第一線。 獲取文件名後,最好使用BufferedReader而不是Scanner。我糾正你的代碼了一下。

import java.io.*; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class AlgorithmTrader { 

    public void Run() { 
     ReadInputData(); 
    } 

    public void ReadInputData() { 

     // create object of scanner class for user input 
     Scanner scan = new Scanner(System.in); 
     // declare file name for input file 
     String inputFileName = ""; 

     // input from user for input file 
     System.out.print("Enter Input File Name: "); 
     inputFileName = scan.nextLine(); 

     // create a new file 
     File csvFile = new File(inputFileName); 
     String line; 
     ArrayList<Stock> list = new ArrayList<>(); 

     try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { 

      System.out.println("Reading file " + csvFile); 

      System.out.println("Skipping title of the CSV file"); 
      // Skip first line because it is title 
      br.readLine(); 

      System.out.println("Converting line to Stock"); 

      while ((line = br.readLine()) != null) { 

       String result[] = line.split(","); 
       String timestamp = result[0]; 
       double close = Double.parseDouble(result[1]); 
       double high = Double.parseDouble(result[2]); 
       double low = Double.parseDouble(result[3]); 
       double open = Double.parseDouble(result[4]); 
       int volume = Integer.parseInt(result[5]); 

       list.add(new Stock(timestamp, close, high, low, open, volume)); 
      } 

      System.out.println("Done"); 

     } catch (FileNotFoundException e1) { 
      System.out.println(" not found."); 
      System.exit(0); 
     } catch (IOException e2) { 
      System.out.println("File can't be read"); 
     } 
    } 
} 
+0

嘿感謝您的幫助 我得到一個錯誤說這裏不允許源代碼級別低於1.7 – Abdoh

+0

@Abdoh在這種情況下,你需要使用的Java是否或1.8+使用try catch塊沒有資源 >>> \t資源規範,否則手動關閉BufferedReader。這是[文檔](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) –