1

For an array, how can i take all the values at even indexes and add to nameArray and all the values at odd indexes and add to scoreArray? I got this code but it isn't working.

String[] inputArray = {"john", "10", "frank", "14"}

for (int j = 0; j == inputArray.length; j++) {
    if ((j % 2) == 0) {
        nameArr.add(inputArray[j]);
        } else {
        scoreArr.add(inputArray[j]);
    }
}
2
  • Do I understand right you want to add the elements of inputArray? But then why use split2[]? Commented Jan 2, 2014 at 22:25
  • sorry just changed the name of the array to inputArray for comfort reading, just failed to change it all, but it's done now. Commented Jan 2, 2014 at 22:36

3 Answers 3

6

You probably mean for (int j = 0; j < inputArray.length; j++)

j == inputArray.length is evaluated to false at the first iteration so your loop doesn't run.

However, you could get rid of the if statement (assuming that your inputArray always contains a name associated a score, i.e always contains pair values) :

for (int j = 0; j < inputArray.length; j+=2) {
    nameArr.add(inputArray[j]);
    scoreArr.add(inputArray[j+1]);
}

Or you could also use a Map<String, Integer> to associate each name with its corresponding score (assuming names are unique) :

for (int j = 0; j < inputArray.length; j+=2) 
     m.put(inputArray[j], Integer.parseInt(inputArray[j+1]));
Sign up to request clarification or add additional context in comments.

2 Comments

Why you got to beat me to it? |=^P
@user3052244 You can read this for more informations about the for statement, docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
1

You probably mean to have a < in your loop and not a == and also, try using inputArray and not split2[] like this:

for (int j = 0; j < inputArray.length; j++) {
    if ((j % 2) == 0) {
        nameArr.add(inputArray[j]);
        } else {
        scoreArr.add(inputArray[j]);
    }
}

Comments

1

What you want to do is look through each element in the array, to do this you want to go through every element starting at 0 and ending at the lengthof the array -1 (because arrays are 0 indexed). Once you are in the loop you want to check if it is an even or odd number using the modulo operator.

for (int j = 0; j < inputArray.length; j++){
    if ((j % 2) == 0) {
        nameArr.add(inputArray[j];
    } else {
        scoreArr.add(inputArray[j];
    }
}

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.