简体   繁体   English

从文件中加载数据并根据第一行的长度插入到数组中

[英]Loading data from a file and inserting into the array depending on the length of the first line

The first line in the file has years and the number of these years indicates the size of the table. 文件的第一行包含年份,这些年份的数量表示表格的大小。 For example, I have the years 2015 2016 2017 then the table will store three numbers. 例如,我有2015年2016年2017年,那么该表将存储三个数字。 Values for variables can be from 1 to number of years. 变量的值可以是1到年数。 If there are fewer than the number of years, the remaining ones are determined on the last of the given values. 如果少于年数,则在给定值的最后一个值上确定剩余的年数。 My problem is that I do not know how to add these numbers to the table. 我的问题是我不知道如何将这些数字添加到表中。

File for example. 例如文件。

YEARS 2015 2016 2017 2018 2019 年份2015 2016 2017 2018 2019

IMP 1.03 1.04 1.07 IMP 1.03 1.04 1.07

public class Main{
 private int years;
 private double [] IMP;
 private StringTokenizer st;
 private String text;

 public void readFromFile(String fname){

 try(BufferedReader br = new BufferedReader(new FileReader(fname))){
  text = br.readLine();
  st = new StringTokenizer(text);
  years = st.countTokens() - 1;

  IMP = new double[years];
  text = br.readLine();
  String split [] = text.split("[ \t]");

  int i =0;
  while(i<years){
   IMP[i] = Double.parseDouble(split[1]); // here is my problem. I dont know how set data here
  }catch (IOException e) {
        e.printStackTrace();
  }
 }
}

Output should be 输出应为

YEARS 2015 2016 2017 2018 2019 年份2015 2016 2017 2018 2019

IMP 1.03 1.04 1.07 1.07 1.07 IMP 1.03 1.04 1.07 1.07 1.07

but now is 但现在是

YEARS 2015 2016 2017 2018 2019 年份2015 2016 2017 2018 2019

IMP 1.03 1.03 1.03 1.03 1.03 IMP 1.03 1.03 1.03 1.03 1.03

IMP[i] = Double.parseDouble(split[1])

Change this to: 更改为:

IMP[i] = Double.parseDouble(split[i+1])

you are only getting the second element from the IMP array which is equal to 1.03. 您只能从IMP数组中获得等于1.03的第二个元素。

EDIT 编辑

Replace the while loop with: 将while循环替换为:

int i = 0;
while(i < split.length){
    IMP[i] = Double.parseDouble(split[i]);
    i++;
}
double lastValue = IMP[i - 1];
while(i < years){
    IMP[i] = lastValue;
    i++;
}

This should do the trick if you want to repeat the last value for the remainder of the number of years. 如果要在剩余的年数中重复最后一个值,这应该可以解决问题。 If you experience any issues, try replacing Double.parseDouble(split[i]) with Double.parseDouble(split[i + 1]) , or try to debug and see what values are in what variables during the execution. 如果遇到任何问题,请尝试将Double.parseDouble(split[i])替换为Double.parseDouble(split[i + 1]) ,或者尝试调试并查看执行期间哪些变量中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM