2013-03-14 27 views
-2

你能幫我這個,我想添加2來自CSV的整數,並將其存儲在txtfile,但問題是這是字符串,如果我把它轉換爲一個整數我有很多錯誤。 。謝謝你們..如何將CSV字符串轉換爲整數並添加它。存儲txtfile

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.util.ArrayList; 
import java.util.List; 

public class CSVReader { 
public static void main (String[]arg)throws Exception { 

    String readFile = "C:/Users/user/Desktop/student.csv"; 
    String writeFile = "C:/Users/user/Desktop/data.txt"; 

    // Read a comma-separated values (CSV) file. 
    BufferedReader CSVFile = new BufferedReader (new FileReader(readFile)); 

    // Read line. 
    String dataRow = CSVFile.readLine(); 

    // Create an array of student 
    List<Student> students = new ArrayList <Student>(); 


    // The while checks to see if the data is null. If 
    // it is, we’ve hit the end of the file. If not, 
    // process the data. 
    while (dataRow !=null){ 
     String [] dataArray = dataRow.split(","); 
     System.out.println(dataRow); 
     Student student = new Student(); 
     student.setStudentName(dataArray[0]); 
     student.setScore1(dataArray[1]); 
     student.setScore2(dataArray[2]); 
     students.add(student); 
     dataRow = CSVFile.readLine(); 
     } 

    // Close the file once all data has been read. 
    CSVFile.close(); 

    StringBuilder sb = new StringBuilder(); 

    FileWriter fw = new FileWriter(writeFile); 
    for (Student s : students){ 
     sb.append(s.studentName); 
     System.out.println(s.studentName + " - " + (s.score1 + s.score2)); 

     // Writing to a text file. 
     fw.write(sb.toString()); 
    } 

    // Close the file once all data has been written. 
    fw.close(); 
} 

} 

輸出:

che,cheche,chet 
    100,100,100 
    100,100,100 
    null - 0 
    null - 0 
    null - 0 

應該BR:

che,cheche,chet 
    100,100,100 
    100,100,100 
    che - 200 
    cheche -200 
    chet - 200 
+1

如果您告訴我們哪些錯誤,這將有所幫助。 – 2013-03-14 10:35:49

+0

如何將字符串轉換爲整數? – PermGenError 2013-03-14 10:36:04

+0

Try student.setScore1(Integer.parseInt(dataArray [1])); – Jayamohan 2013-03-14 10:51:15

回答

0

你可以試試

int number = Integer.parseInt("your string here"); 

例子:

String one = "1"; 
    String two = "2"; 
    System.out.println(Integer.parseInt(one) + Integer.parseInt(two)); 
+0

它用於添加兩個整數值。 – 2013-03-14 11:22:06

+0

對不起,誤解了你的帖子;-) – 2013-03-14 12:07:56

0

你在代碼所做的一些錯誤。

  1. 學生類中的分數變量應該是整數。
  2. 要將字符串轉換爲Integer,您需要使用Integer.parseInt 方法。理想情況下,您的轉換應該在您設置得分值的 階段。
  3. 爲什麼要將學生對象添加到ArrayList中。你不能 直接寫入文本文件?
1

如果您所提供的信息是正確的,那麼你的主要問題是CSV數據是柱狀的格式,而不是一個典型的行格式。我的意思是,第一行是名字,下一行是分數。每個「列」數據與相同索引處的「標題」匹配。

您的數據。例如:

che, cheche, chet -- row[0] 
100, 100, 100  -- row[1] 
100, 100, 100  -- row[2] 

所以行[0]這個名字,但你解析TE數據,如果行的第一個產品名稱,第二和第三項是分數 - 這不是基於這個樣本數據的情況。

如果你想得分,你需要得到每一行的正確索引 - 所以che會是row [1] [0]和row [2] [0]。

如果事實確實如此,那麼您需要處理第一行以獲取名稱,然後您需要處理剩餘的行以獲取分數。

+0

我會試試你的建議謝謝:) – 2013-03-14 12:31:34