Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将文件中的数字存储到数组中_Java_Arrays_File - Fatal编程技术网

Java 如何将文件中的数字存储到数组中

Java 如何将文件中的数字存储到数组中,java,arrays,file,Java,Arrays,File,我不知道这是怎么回事。 我必须读入一个文件(文件中有数字)并将数字存储到数组中。 文件如下: 我知道第一个数字是零,我不能更改文件中的数字或数字顺序 文件 0 10 20 30 40 50 60 70 80 90 这是我的密码: import java.util.*; import java.io.*; public class Check { public static void main(String[] args) throws FileNotFoun

我不知道这是怎么回事。 我必须读入一个文件(文件中有数字)并将数字存储到数组中。 文件如下: 我知道第一个数字是零,我不能更改文件中的数字或数字顺序

文件
0
10
20
30
40
50
60
70
80
90
这是我的密码:

import java.util.*;
import java.io.*;

public class Check {

    public static void main(String[] args) 
           throws FileNotFoundException {
         Scanner input = new Scanner(new File("scores1.txt"));
         process(input);
    }

    public static void process(Scanner input) {
        int[] numbers = new int [input.nextInt()];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }
        Arrays.sort(numbers);
        System.out.print("numbers: "+Arrays.toString(numbers));   
   }
}
import java.util.*;
导入java.io.*;
公共类检查{
公共静态void main(字符串[]args)
抛出FileNotFoundException{
扫描仪输入=新扫描仪(新文件(“scores1.txt”);
过程(输入);
}
公共静态无效处理(扫描仪输入){
int[]number=new int[input.nextInt()];
for(int i=0;i
这是输出: 编号:[]


我假设声明数组有问题。

文件中的第一个值是0

int[] numbers = new int [input.nextInt()]; // this input.nextInt() gets the first line
您正在创建一个大小为0的数组

因为文件中有10个数字。初始化为大小10

int[] numbers = new int [10];

我的建议是使用
ArrayList

public static void process(Scanner input) {
    List list = new ArrayList();
    while(input.hasNextInt()){
        list.add(input.nextInt());
    }
    Collections.sort(list);
    System.out.print("numbers: " + list);   
}

问题是,文件的第一个值是
0
。所以数组大小是
0
。更改第一个值,以便将其余值放入数组。

公共静态无效过程(扫描仪输入){
public static void process(Scanner input) {
        List<Integer> number = new ArrayList<Integer>();
        while(input.hasNext()) {
            number.add(input.nextInt());//i hope all ints are there in the file
        }
        int[] numbers = number.toArray(new int[number.size])
        //then do sort and all   
   }
列表编号=新的ArrayList(); while(input.hasNext()){ number.add(input.nextInt());//我希望所有int都在文件中 } int[]number=number.toArray(新int[number.size]) //那就分类吧 }

希望这会有帮助

是文件的第一个值,是数组的大小吗?显示您的文件内容。输入文件内容请同时共享该文件。因此,第一个数字是0,您有一个0大小的数组将输入文件第一行中的“0”更改为“9”,这样就可以了…仅更改第一个值并不能解决整个问题。若第一个值设为1,那个么数组的大小将为1。因此,只有1个值将从文件中读取并插入到数组中。