[英]Reading ints from file and storing value to an array
I have a file, lets say data.txt which contains data in the following format 我有一个文件,可以说data.txt,其中包含以下格式的数据
1 12
2 84
3 82
9 82
3 1
3 2
The first number indicates what index of the array the second number should be added to. 第一个数字指示第二个数字应添加到数组的哪个索引。 I am having trouble working this out... I wanted to create a method that parses through the .txt file and adds the values to the appropriate index then returns the array with all the numbers added up. 我在解决这个问题时遇到了麻烦...我想创建一个方法来解析.txt文件并将值添加到适当的索引,然后返回包含所有数字的数组。
Try this. 尝试这个。
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
Here sc.nextLine().split("\\\\s");
这里sc.nextLine().split("\\\\s");
reads each line and spits that line by space into an array line[]
. 读取每行并将其逐行插入数组line[]
。 line[0]
will have index and line[1]
will have element. line[0]
行将具有索引, line[1]
行将具有元素。 It will be in form of String. 它将采用字符串形式。 It can be converted to int
by Integer.parseInt()
. 可以通过Integer.parseInt()
将其转换为int
。 ele
store the element and index
stores the index of that element after converting to int
. ele
存储元素,而index
存储转换为int
后存储该元素的索引。
Some index are not specified in the file so its value will be 0
. 文件中未指定某些索引,因此其值为0
。
Some of the index in your code has repeated so that values will be overwritten. 您的代码中的某些索引已经重复,因此值将被覆盖。
I took the text file as 1 12 2 84 3 86 4 17 5 18 9 10 我将文本文件作为1 12 2 84 3 86 4 17 5 18 9 10
which contains 12 numbers. 其中包含12个数字。
Please dont give repeated index 请不要重复索引
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));
}
}
output: [1, 12, 2, 84, 3, 86, 4, 17, 5, 18, 9, 10] 输出:[1、12、2、84、3、86、4、17、5、18、9、10]
[1, 2, 3, 4, 5, 9] [1、2、3、4、5、9]
[0, 12, 84, 86, 17, 18, 0, 0, 0, 10] [0,12,84,86,17,18,0,0,0,10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.