java - 从文件中读取数据并存储在两个数组中

标签 java arrays

你好,我在尝试读取文件并获取文件的两列并将它们分别放入自己的数组中时遇到问题。任何帮助,将不胜感激!谢谢!

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    // TODO Auto-generated method stub

    System.out.println("Please enter the name of the file to be read");
    String fileName = keyboard.nextLine();
    Scanner chirping = null;//user input for file name
    boolean fileValue = false; //this makes the value false until the correct file name is inputed
    while(!fileValue) {
        try {
            FileReader dates = new FileReader(fileName); // connects to the user inputted file
            chirping = new Scanner(dates); //scans the file
            fileValue = true; //turns file value to true which takes us out of the while loop

            }//end try
        catch(IOException e)  {
            System.out.println("File Not Found, Please Try Again: ");
            fileName = keyboard.nextLine();
        }//end catch
}// end while
    double[] dataSet = new double[30];
    double[] chirpFreq = new double[30];
    double[] temp = new double[30];
    //double[] temp = new double[chirping.nextInt()];
        for(int i = 0; chirping.hasNextDouble(); i++) {
                dataSet[i] = chirping.nextDouble();
        }

        for(int j = 0; j <= dataSet.length; j++) {
            if(j%2 == 0) {
                chirpFreq[j] = dataSet[j];
            }
            else {
                temp[j] = dataSet[j];
            }
        }

        for(int i = 0; i <= chirpFreq.length; i++) {
            System.out.print(chirpFreq[i]+ " ");
        }
        chirping.close();
}

//这些是我试图排序到两个单独的数组中的值

20 88.6 16 71.6 19.8 93.3 18.4 84.3 17.1 80.6 15.5 75.2 14.7 69.7 17.1 82 15.4 69.4 16.2 83.3 15 79.6 17.2 82.6 16 80.6 17 83.5 14.4 76.3

最佳答案

我通常不使用 nextDouble() 来读取文件,所以我不知道您的问题到底是什么,但您可以将代码重构为:

double[] firstColumn = new double[30];
double[] secondColumn = new double[30];

String line = "";
int i = 0;

// keep reading until there is nothing to read
while( (line = chirping.nextLine()) != null ) {

    // this is a regex that splits the line into an array based on whitespace 
    // just use " " if your data is separated by space or "\t" if tab
    String[] columns = line.split("\\s+");

    firstColumn[i] = Double.parseDouble(columns[0]);
    secondColumn[i++] = Double.parseDouble(columns[1]);
}

chirping.close();

关于java - 从文件中读取数据并存储在两个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61198591/

相关文章:

java - 用于查找具有随机中心的特定字符串的正则表达式

java - 如何记录 JDBC 连接 Activity ?

c++ - 在类中使用指针作为私有(private)指针来访问 C++ 中的数组

java - 如何在 Java 中对整数进行排序而不使其成为数组或列表?

c++ - 如何在 json-Glib 中打印 Jsonarray?

java - 如何在 Windows 中使用粗略计时器分辨率编写 Java Thread.sleep() 代码

java - 多个实例与单个静态实例

java - Java,以初始值设定项列表格式将2d数组传递给方法

php - 如何从多维数组中删除重复项和原始数组?

javascript - "with"Knockout Js 中多维数组上的数据绑定(bind)