0

I just started learning Java with the goal to make games for Android. I'm taking an online course, where I am provided with a task and later an evaluation of some sort.

This is what I've done so far:

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++){

What I would like to do is to add something like this to my code, but automated:

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]
...}

Thank You in advance!

2 Answers 2

4

try this

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++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

That should do it. So embarrassed that I didn't see that myself :P. Also, for anyone looking at this question, you should also add pie[0 + i], pie[1+i], pie[2+i], pie[3+i]..
0

Here's two sides of the same coin. Both assume pie.length is a multiple of 8, since your code also appears to assume that.

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];
}

or

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.