[英]Reading ints from file and storing value to an array
我有一個文件,可以說data.txt,其中包含以下格式的數據
1 12
2 84
3 82
9 82
3 1
3 2
第一個數字指示第二個數字應添加到數組的哪個索引。 我在解決這個問題時遇到了麻煩...我想創建一個方法來解析.txt文件並將值添加到適當的索引,然后返回包含所有數字的數組。
嘗試這個。
Scanner sc = new Scanner(new File("data.txt"));
int[] arr = new int[10];
while(sc.hasNextLine()) {
String line[] = sc.nextLine().split("\\s");
int ele = Integer.parseInt(line[1]);
int index = Integer.parseInt(line[0]);
arr[index] = ele;
}
int sum = 0;
for(int i = 0; i<arr.length; i++) {
sum += arr[i];
System.out.print(arr[i] + "\t");
}
System.out.println("\nSum : " + sum);
return sum;
0 12 84 2 0 0 0 0 0 82
Sum : 180
這里sc.nextLine().split("\\\\s");
讀取每行並將其逐行插入數組line[]
。 line[0]
行將具有索引, line[1]
行將具有元素。 它將采用字符串形式。 可以通過Integer.parseInt()
將其轉換為int
。 ele
存儲元素,而index
存儲轉換為int
后存儲該元素的索引。
文件中未指定某些索引,因此其值為0
。
您的代碼中的某些索引已經重復,因此值將被覆蓋。
我將文本文件作為1 12 2 84 3 86 4 17 5 18 9 10
其中包含12個數字。
請不要重復索引
public class FileArray {
public static void main(String[] args) throws FileNotFoundException {
FileReader file=new FileReader("data.txt");
int[] array=new int[12]; //i took size of array as total numbers in text file,
int i=0;
try{
Scanner sc=new Scanner(file);
while(sc.hasNext()){
array[i]=sc.nextInt();
i++;
}
sc.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(Arrays.toString(array));
int size=(array.length)/2;
int[] index=new int[size];
int j=0;
for(int k=0;k<array.length;k++)
{
if(k%2==0)
{
index[j]=array[k];
j++;
}
}
System.out.println(Arrays.toString(index));
int[] res=new int[10];
int m=1;
for(int l=0;l<index.length;l++)
{
res[index[l]]=array[m];
m+=2;
}
System.out.println(Arrays.toString(res));
}
}
輸出:[1、12、2、84、3、86、4、17、5、18、9、10]
[1、2、3、4、5、9]
[0,12,84,86,17,18,0,0,0,10]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.