根据行长度更改最终数组

时间:2014-10-24 04:30:57

标签: java arrays arraylist

我有一个包含3个标题的文本文件,如

serviceid, jobid, serviceNumber 
001, 5, 280

这将存储本周的机械工作。只能有一个jobid / serviceid,但可以有多个服务号。

我有String[]持有拆分然后分配这些值。但是,诀窍是一些行有多个serviceNumber,如

serviceid, jobid, serviceNumber 
002, 8, 250,280,290

如何扩展我的数组以保存在int[] serviceNumberArray的路上遇到的任何额外代码?并且,我不允许使用ArrayList。这是我目前的代码:

String jobs; //holds extracted textfile values
int jobID;           //holds job id
int serviceID;       //holds service id
int[] serviceNumber; //holds all service numbers

String[] splitJobs = new String[2]; //holds all split jobs
splitJobs = jobs.split(","); //splits jobs and sets delimiter as comma
this.serviceid = Integer.parseInt(splitJobs[0]);
this.jobID = Integer.parseInt(splitJobs[1]);
this.serviceNumber = Integer.parseInt(splitJobs[2]);

2 个答案:

答案 0 :(得分:1)

首先,您的代码看起来像Java,所以我将假设您需要的答案。然后,这个

String[] splitJobs = new String[2]; // <-- array reference.

具有欺骗性。你扔掉它,你可以完全消除那条线,你应该移动你的serviceNumber声明。我想你想要的东西( note 正则表达式将删除逗号周围的任何空格),

// String[] splitJobs = new String[2];
String[] splitJobs = jobs.split("\\s*,\\s*"); // <-- creates a "dynamic" array.
this.serviceid = Integer.parseInt(splitJobs[0]);
this.jobID = Integer.parseInt(splitJobs[1]);
int[] serviceNumber = new int[splitJobs.length - 2];
for (int i = 2; i < splitJobs.length; i++) {
    this.serviceNumber[i - 2] = Integer.parseInt(splitJobs[i]);
}

也可以写这个循环,

for (int i = 0; i < splitJobs.length - 2; i++) {
    this.serviceNumber[i] = Integer.parseInt(splitJobs[i + 2]);
}

答案 1 :(得分:0)

尝试以下代码

public class Test {
  public static void main(String[] args) {

    String jobs = "1,2,3,4,5,6"; //holds extracted textfile values

    int jobID;           //holds job id
    int serviceID;       //holds service id
    int[] serviceNumber; //holds all service numbers

    String[] splitJobs = jobs.split(","); //splits jobs and sets delimiter as comma

    serviceID = Integer.parseInt(splitJobs[0]);

    jobID = Integer.parseInt(splitJobs[1]);

    serviceNumber = new int[splitJobs.length - 2];

    for(int i = 2; i < splitJobs.length; i++){
        serviceNumber[i -2] = Integer.parseInt(splitJobs[i]);
    }
  }

}

祝你好运!试着发表意见......