2017-11-04 8 views
0

私はJavaで初心者であり、これらの2つの問題に固執していますので、私は をCSVファイルから1行ずつ読み込みます。NumberFormatExceptionは、JavaでCSVファイルを読み取るとき

ファイルでは、最初の行がStringで、列がdoubleです。 問題は最初の行を読むときです。タイトルをダブルで読むとエラーになります。

それはCSVが

私が得たエラーファイルであるところで、これらはスレッド「メイン」java.lang.NumberFormatExceptionに 例外を下回っている:これは

最初のエラーである「CLOSE」:入力文字列の場合java.lang.Double.parseDouble(Double.java:510)で

サードエラー>>フォース

- sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimaのl.java:1222)における第二の誤差>>エラー>>>でAlgorith AlgorithmTrader.Run(AlgorithmTrader.java:16)

最終エラー>> SimpleAlgorithmTradingPlatform.main(SimpleAlgorithmTradingPl atform.java:15)でmTrader.ReadInputData(AlgorithmTrader.java:63)

フィフスエラー>>

したがって、ファイルの最初の行には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

すべての関連情報を質問に追加してください。それは\t \t \t /この行でAlgorithmTrader.ReadInputData(AlgorithmTrader.java:63)ライン63 – c0der

+0

は おかげで、あなたのコード内でこの行をチェックし – Abdoh

+0

を私が編集していると、うまくいけば、あなたは私がやろうとしているかを理解コメント\t double close = Double.parseDouble(result [1]); –

答えて

0

だけでなく、別のファイルにmainメソッドを持っていますあなたのCSVファイルを削除してください。 ;)

あなたのエラー(おそらくすべて)があなたのクラスから来る可能性が高いようです。それはあなたのgetterとセッターに注意が必要ですが、別の投稿された質問のためです。欠けているものもありますが、おそらくこれが選択肢です。

ループの間に、1つのScannerオブジェクトと1つのでこのタスクを実行できるはずです。ユーザの入力とファイルの読み込みに同じScannerオブジェクトを使用しますが、それはとにかく再初期化されます。

以下のコードは、それを行うための一つの方法である:

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

Heyあなたの助けをありがとうございます。エラーが出ました>>>リソースの仕様は、1.7より下のソースレベルでは許可されていません。 – Abdoh

+0

JDKのバージョンに合わせてコードを変更しました。 – DevilsHnd

3

あなたは最初の行をスキップされていませんここ

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

ので、あなたはNumberFormatExceptionがを持っています。 ファイル名を取得した後、スキャナの代わりにBufferedReaderを使用する方がよいでしょう。私はコードを少し修正しました。

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

ねえ、私はエラーを得たあなたの助け のおかげであなたは、リソースなしでのJava 1.8+または使用のtry catchブロックかどうかを使用する必要があります。この場合、1.7 – Abdoh

+0

@Abdoh以下のソースレベルのためにここでは使用できません >>> \tリソースの仕様を言いますそれ以外の場合は、BufferedReaderを手動で閉じます。ここには[documentation](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)があります。 –

関連する問題