![](/img/trans.png)
[英]Android Java - Reading in Text File of Integers, Storing Integers in Array, and Graphing Them
[英]Storing integers inside a data file into an array Java
我正在嘗試將數據文件中的整數存儲到數組中。 我正在使用 Java Eclipse IDE。
這是我的數據文件:
(oddsAndEvens.dat)
2 4 6 8 10 12 14
1 2 3 4 5 6 7 8 9
2 10 20 21 23 24 40 55 60 61
這是我的代碼:
import java.io.File;
import java.util.Arrays;
import java.io.IOException;
import java.util.Scanner;
public class OddsAndEvens {
public static void main(String[] args) throws IOException {
Scanner file = new Scanner(new File("oddsAndEvens.dat"));
int count, num = 0;
int[] newRay = null;
while (file.hasNext()) {
String line = file.nextLine();
Scanner chop = new Scanner(line);
count = 0;
while (chop.hasNextInt()) {
num = chop.nextInt();
count++;
newRay = new int[count];
int j = 0;
for (int i = 0; i < count; i++) {
newRay[j] = num;
j++;
}
}
System.out.println(Arrays.toString(newRay));
}
}
}
我的 output 是這樣出來的:
[14, 14, 14, 14, 14, 14, 14]
[9, 9, 9, 9, 9, 9, 9, 9, 9]
[61, 61, 61, 61, 61, 61, 61, 61, 61, 61]
我正在尋找的是:
[2, 4, 6, 8, 10, 12, 14]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 10, 20, 21, 23, 24, 40, 55, 60, 61]
如何將數據文件中每一行的這些數字集轉換為數組? 有更簡單的方法嗎?
您的問題是您有一個循環讀取所有數字並將它們分配給num
,另一個循環將num
存儲在數組中的每個索引處。 每個數組組件一次只能保存一個數字,因此每次分配它們時,它們以前的值都會被覆蓋(即丟失),因此最終數組只保存從掃描儀讀取的最后一個數字。
要解決此問題,您應該只使用一個循環,該循環讀取一個數字並將其存儲在數組中,然后循環的下一次迭代讀取下一個數字。 您不應該有一個循環在數組中的每個索引處寫入相同的值。
您可以讀取每一行並將其存儲在字符串數組中,方法是用空格將其拆分,然后將其轉換為 integer,這是您的操作方法。\
import java.io.File;
import java.util.Arrays;
import java.io.IOException;
import java.util.Scanner;
public class OddsAndEvens {
public static void main(String[] args) throws IOException {
Scanner file = new Scanner(new File("oddsAndEvens.dat"));
int[] newRay = null;
while (file.hasNext()) {
String line = file.nextLine();
String[] str = line.split("\\s+");
newRay = new int[str.length];
for (int i = 0; i < str.length; i++) {
newRay[i] = Integer.valueOf(str[i]);
}
System.out.println(Arrays.toString(newRay));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.