2015-10-22 24 views
1

此代碼應該讀取csv文件,使用數組將所有Axillary(Array [2])添加在一起並查找平均值。讀取CSV文件和IF語句值0?

唯一的不同就是使用了IF語句,因爲我想根據(Array [3])的值將數據拆分爲兩個不同的變量,它們將是1或2,並查找它們的平均值分別。

當我運行此代碼時,兩者的輸出值均爲0。

package javainputoutput; 

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

public class JavaInputOutput 
{ 
public static void main(String[] args) 
{ 
    int totalOverAxillary = 0; 
    int countOverAxillary = 0; 
    int totalLessAxillary = 0; 
    int countLessAxillary = 0; 

    String fileName = "haberman.txt"; 
    try 
    { 
     Scanner InputStream = new Scanner(new File(fileName)); 

     while (InputStream.hasNextLine()) 
     { 
      String line = InputStream.nextLine(); 
      String[] ary = line.split(","); 

      int noPosAxillary = Integer.parseInt(ary[2]); 
      int survivalStatus = Integer.parseInt(ary[3]); 

      if(survivalStatus == 1) 
      { 
       totalOverAxillary =+ noPosAxillary; 
       countOverAxillary++; 
      } 
      else if(survivalStatus == 2) 
      { 
       totalLessAxillary =+ noPosAxillary; 
       countLessAxillary++; 
      } 
     } 

     InputStream.close(); 

     int aveOverAxillary = totalOverAxillary/countOverAxillary; 
     int aveLessAxillary = totalLessAxillary/countLessAxillary; 

     System.out.print("The average number of positive axillary nodes " 
         + "for patients that survived 5 years or longer is " 
         + aveOverAxillary); 
     System.out.println(); 
     System.out.print("The average number of positive axillary nodes " 
         + "for patients that died within 5 years is " 
         + aveLessAxillary); 
    } 
    catch(FileNotFoundException e) 
    { 
     System.out.println("Cannot find file " + fileName); 
    } 
    catch(IOException e) 
    { 
     System.out.println("Problem with input from file " + fileName); 
    } 
} 

} 

回答

0

看來你搞砸了+=運營商。取而代之的是:

totalOverAxillary =+ noPosAxillary; 

它應該是這樣的:

totalOverAxillary += noPosAxillary; 

你必須在兩個地方上面的錯誤,請務必同時修改。

這樣做的效果是總值將等於最後的值而不是總和。 而當您將這些值除以計數值時, 可能計數值小於值,則 和整數除法結果爲零。

+0

啊這麼簡單的錯誤,我看不到它! 這就是我得到的試圖找到一個錯誤在凌晨3點 謝謝 –

+0

它不會讓我再過5分鐘,但當它的時候我會 –