有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java试图使选定文件的数据成为数组,但如何实现?

嗯,基本上我想能够选择一个有一堆数字的文件,打印它的名称和目录,然后找到模式,我想我已经弄明白了,但是创建数组来保存我的数据让我很为难。我觉得答案就在我面前,它真的让我烦恼,谢谢你的帮助

import java.io.*;
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;

 public class ModeFinder 
 {
    public static void main(String args[]) 
    {
        String filename;

        FileDialog filePicker = new FileDialog(new JFrame());
        filePicker.setVisible(true);

        filename = filePicker.getFile();
        String folderName = filePicker.getDirectory();
        filename = folderName + filename;
        System.out.println("filename = " +filename);

        File inputFile = new File(filename);
        Scanner fileReader;
        try
        {
            fileReader = new Scanner(inputFile);
        }
        catch (FileNotFoundException excp)
        {
            System.out.println("That's no file...");
        }

        int size = ;
        double[] a = new double[size];
        int maxValue = 0,
                maxCount = 0;
        for (int i = 0; i < a.length; ++i) {
            int count = 0;
            for (int j = 0; j < a.length; ++j) {
                if (a[j] == a[i]) ++count;
            }
            if (count > maxCount) {
                maxCount = count;
                maxValue = (int) a[i];
            }
        }
        System.out.println("The most common grade is: " +maxValue);
    }
}

如果我不需要制作数组,我不介意你这么说。我只需要一种方法,使数字从一个文件被读取,并用于找到模式说,数字。只是一个刷新,模式是数据集中出现最多的数字


共 (1) 个答案

  1. # 1 楼答案

    如果你致力于使用数组,你可以通过文件两次;一次获取文件中的双倍数,另一次实际读取值。此方法将计算给定文件中的双倍数:

    public static int countDoubles(File file) throws FileNotFoundException
    {
        // Create a scanner to read the file.
        Scanner reader = new Scanner(file);
    
        // Count of the doubles in the file.
        int count = 0;
    
        while (reader.hasNextDouble())
        {
            // Consume each double and increment the counter.
            count++;
            reader.nextDouble();
        }
    
        reader.close();
        return count;
    }
    

    此方法将从文件中读取双精度:

    public static double[] readDoubles(File file, int numberOfDoubles) throws FileNotFoundException
    {
        // Create a scanner to read the file.
        Scanner reader = new Scanner(file);
    
        // Create an array to store the values.
        double[] values = new double[numberOfDoubles];
    
        for (int i = 0; i < values.length && reader.hasNextDouble(); ++i)
        {
            // Consume each value and insert it into the array.
            values[i] = reader.nextDouble();
        }
    
        reader.close();
        return values;
    }
    

    然而,使用一个可以动态调整大小的结构(比如^{)会更简单(也更健壮)