請我想調(diào)整這個從文件中讀取整數(shù)的代碼。我希望代碼能夠檢測數(shù)據(jù)集的數(shù)量 (n),而不必像下面那樣手動輸入數(shù)字 (4000)雙[]高=新雙[4000];public class Extracto { public static void main(String[] args) throws IOException { File fil = new File("C:\\Users\\Desktop\\kaycee2.csv"); FileReader inputFil = new FileReader(fil); BufferedReader in = new BufferedReader(inputFil); double[] tall = new double[4000]; String s = in.readLine(); int i = 0; while (s != null) { // Skip empty lines. s = s.trim(); if (s.length() == 0) { continue; } tall[i] = Double.parseDouble(s); // This is line 19. // System.out.println(tall[i]); s = in.readLine(); i++; }我期望調(diào)整后的代碼能夠獲取數(shù)據(jù)長度,而無需手動將其放入,如下面的代碼所示,長度為 4000。雙[]高=新雙[4000];
1 回答

海綿寶寶撒
TA貢獻1809條經(jīng)驗 獲得超8個贊
使用列表而不是數(shù)組。
? ? File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
? ? FileReader inputFil = new FileReader(fil);
? ? BufferedReader in = new BufferedReader(inputFil);
? ? ArrayList<Double> tall = new ArrayList<>();
? ? while(in.ready()){?
? ? ? ? String s = in.readLine().trim();
? ? ? ? if(!s.isEmpty()){
? ? ? ? ? ?tall.add(Double.parseDouble(s);
? ? ? ? }?
? ? }
如果您使用列表,您的代碼可以進一步壓縮。當讀取的字符串不是數(shù)字時,還應在事件中添加 try-catch。
添加回答
舉報
0/150
提交
取消