0

我刚开始学习 Java,目标是为 Android 制作游戏。我正在参加在线课程,在那里我获得了一项任务,然后是某种评估。

这是我到目前为止所做的:

public String[] pie;
public Scanner x;
public String[] name;
public String[] name1;
public String[] name2;
public int[] year;
public int[] numb;
public String[] language;
public boolean[] read;
public int[] rating;

   public void openfile(){
    try{x = new Scanner(new File("Raamatukogu.txt"));}
    catch(Exception e){
        System.out.println("no file was found");}}

public void readfil(){
    while(x.hasNext()){
        String rida = x.nextLine();
        pie = rida.split("#");
        for(int i = 0; i < pie.length ; i++){

我想做的是在我的代码中添加这样的东西,但是自动化:

name[0] = pie[0]
name1[0] = pie[1]
name2[0] = pie[2]
year[0] = pie[3]
numb[0] = pie[4]
language[0] = pie[5]
read[0] = pie[6]
rating[0] = pie[7]

name[1] = pie[8]
name1[1] = pie[9]
name2[1] = pie[10]
year[1] = pie[11]
numb[1] = pie[12]
language[1] = pie[13]
read[1] = pie[14]
rating[1] = pie[15]

name[2] = pie[16]
name1[2] = pie[17]
...}

先感谢您!

4

2 回答 2

4

尝试这个

int j=0;
for(int i=0;i<pie.length;i++){
    name[j] = pie[0];
    name1[j] = pie[1];
    name2[j] = pie[2];
    year[j] = pie[3];
    numb[j] = pie[4];
    language[j] = pie[5];
    read[j] = pie[6];
    rating[j] = pie[7];
    j++;
}
于 2012-04-28T19:12:41.683 回答
0

这是同一枚硬币的两个面。两者都假设pie.length是 8 的倍数,因为您的代码似乎也假设了这一点。

for (int i=0; i<pie.length/8; i++) {
    int index = i * 8;
    name[i] = pie[index];
    name1[i] = pie[index+1];
    name2[i] = pie[index+2];
    year[i] = pie[index+3];
    numb[i] = pie[index+4];
    language[i] = pie[index+5];
    read[i] = pie[index+6];
    rating[i] = pie[index+7];
}

或者

for (int i=0; i<pie.length; i=i+8) {
    int index = i/8;
    name[index] = pie[i];
    name1[index] = pie[i+1];
    name2[index] = pie[i+2];
    year[index] = pie[i+3];
    numb[index] = pie[i+4];
    language[index] = pie[i+5];
    read[index] = pie[i+6];
    rating[index] = pie[i+7];
}
于 2012-04-28T23:45:40.217 回答