【问题标题】:How to Read Text File From a Scanner and Convert Into an Int Array Java如何从扫描仪读取文本文件并转换为 Int 数组 Java
【发布时间】:2019-04-12 03:04:54
【问题描述】:

我一直在尝试创建一个 Java 程序来读取包含 100 个整数的文件“100.txt”,然后将它们存储到一个 int 数组中。稍后,我将让它打印数组并对数组中的数字进行排序,但我想让它读取文本文件并将数字存储在数组中并首先将其转换为 int 数组。我该怎么做?

我尝试了几种不同的方法。我知道如何从 Scanner 读取文本文件并创建一个数组,但我从未更改过类型(在本例中,String 为 int)。如果你们中的任何人都可以帮助我并就如何解决这个问题给我一些指示,那将不胜感激。

try
{
    File file = new File("100.txt");
    Scanner input = new Scanner(file);

    while (input.hasNextLine())
    {
        String line = input.nextLine();
        System.out.println(line);
    }
    input.close();  
    }
    catch (Exception ex)
        {
        ex.printStackTrace();
    }
    int[] array = new int[file.length];
    int i, n = array.length;
    for (i = 0; i < n; i++)
    {    array[i] = Integer.parseInt(file[i]);
    }
}

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    假设您知道文件的行数,您可以使用此代码。另请注意,将其作为 BufferedReader 读取并将其传递给扫描仪会更有效。

    我尽量保持简单,但如果您有任何疑问,请随时提出。

    public int[] readFile(String filePath)throws Exception
        {
            int[] array = new int[100];
            Scanner sc = new Scanner(new BufferedReader(new FileReader(new File(filePath))));
            for(int i=0;sc.hasNextLine();i++) 
            {
            array[i]=Integer.parseInt(sc.nextLine());
            }
            return array;
        }
    

    【讨论】:

    • 如果没有,你可能应该使用列表并将其转换为 int 数组
    【解决方案2】:

    试试这个

    public Integer[] ReadFromFile(String fileName) {
            List listInt = new LinkedList<Integer>();
            try {
                Scanner input = new Scanner(new File(fileName));
    
                while (input.hasNextLine()) {
                    String value = input.nextLine();
                    listInt.add(Integer.parseInt(value));
                    System.out.println(value);
                }
                input.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return (Integer[]) listInt.stream().toArray();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多