0
class Blue_ManTest{

    public static void main(String[] args){
        String name = "I LOVE JAVAWORLD";
        int index1 = name.indexOf(" ");
        int index2 = name.lastIndexOf(" ");
        String str1 = name.substring(0, index1);
        String str2 = name.substring(index1 + 1, index1+ 5);
        String str3 = name.substring(index2 + 5);
        System.out.println(str3 + ", " + str1 + " " + str2 + ".");
    }
}   

I am having trouble figuring out what would be the output of this program I think I know it but I am not sure.

I did this I Love JavaWorld with 0 corresponding to j and 15 to D with 1 being the space between.

for str1 I get I

for str2 I get Love

but for str3 I get avaWorld

But str3 seems wrong to me as it would print out.

avaWorld, I  Love.    
4
  • Why dont you just run it? Commented Sep 14, 2013 at 22:06
  • 2
    I ran it and got WORLD, I LOVE. Commented Sep 14, 2013 at 22:06
  • What is the intended output? Commented Sep 14, 2013 at 22:09
  • String 3 is confusing me how does it work because it starts index 2 which is L plus 5 which is 7 and give you J Commented Sep 14, 2013 at 22:10

1 Answer 1

1

Your str3 variable is taking a substring that starts at index2 + 5 where index2 is the index of the last space in your input string:

int index2 = name.lastIndexOf(" ");

That is, index2 is 6. And of course 6 + 5 is 11.

Sign up to request clarification or add additional context in comments.

3 Comments

and index 2 is that not L in I LOVE JAVAWORLD ?
Yes I think what confused me is that index1 = name.indexOf(" "); the quotation marks mean blank because they have nothing inside.
The quotation marks don't have nothing inside, they have a single space character.

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.