0

Lets say I have a string array called ar1, ar1[x] is "Harry Potter"

Now lets say I have another string array called ar2, I want ar2[x] to equal "Harry". How would I do this?

Here is something I tried, it did not work.

String ar2[] = new String[10];
int x = 0;        
while(x<9){
        ar2[x] = ar1[x].split(" ").toString();
        x++;
        System.out.println(ar2[x]);}}}

the out put was 9 null's.

3
  • 1
    Your problem is that you print value after incrementing index. Commented Mar 31, 2015 at 22:40
  • now if i wanted "Potter" how would i do this? thankyou Commented Mar 31, 2015 at 23:33
  • 1
    ar1[x].split(" ")[1] Commented Apr 1, 2015 at 8:39

1 Answer 1

1

It looks like you're calling toString() on a String array. The 'split()' method Returns a String array, and what you want is the first element in the array resulting from the split.

It looks like you want something like this:

    String ar2[] = new String[ar1.length]; //better if this is not hard coded to 10
    int x = 0;        
    while(x < ar1.length){
            String[] temp = ar1[x].split(" ");
            ar2[x] = temp[0];
            x++; //Moved in initial edit to fix null printing
     }

     //moved printing code out of loop where populating array occurs 
     for (int i = 0; i < ar2.length; i++){
            System.out.println(ar2[i]);
     }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Sasha Salauyou, fixed.
this also prints just null
thank you guys a simple error by me ): thank you sasha and daniel
might add a note that the x++ had to moved.

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.