【问题标题】:How to store numbers from a file into an array如何将文件中的数字存储到数组中
【发布时间】:2013-12-09 05:40:50
【问题描述】:

我无法弄清楚这有什么问题。 我必须读入一个文件(该文件有数字)并将数字存储到一个数组中。

这是文件:

http://dl.dropboxusercontent.com/u/31878359/courses/15/scores1.txt

我知道第一个数字是零,我无法更改文件中的数字或数字顺序。

文件
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));   
   }
}

这是输出:

数字:[]

我假设声明数组有问题。

【问题讨论】:

  • 是文件的第一个值,是数组的大小?显示您的文件内容。
  • 请输入文件内容
  • 请也分享文件。
  • 所以第一个数字是 0,你有一个 0 大小的数组
  • 把输入文件第一行的“0”改成“9”就可以了……

标签: java arrays file


【解决方案1】:

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

【讨论】:

  • 只改变第一个值并不能解决整体问题。如果第一个值设为 1,则数组的大小将为 1。因此只会从文件中读取 1 个值并插入到数组中。
【解决方案2】:

文件中的第一个值为0。

int[] numbers = new int [input.nextInt()]; // this input.nextInt() gets the first line

你正在制作一个大小为 0 的数组

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

int[] numbers = new int [10];

【讨论】:

    【解决方案3】:
    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   
       }
    

    希望这会有所帮助

    【讨论】:

      【解决方案4】:

      我的建议是使用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);   
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-04
        • 2017-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多