-4
public void display()
{

    super.display();

    String str =  super.getChoices();

    System.out.println(str);

    while(!str.equals("")) 
    { 
        int a = str.indexOf(" ");
        System.out.println(str.substring(0, a));
        String sentence = str.replaceFirst(str, str.substring(a));
        System.out.println(sentence);
    }
} 

I have a String str containing "Apple Banana Orange". I want to system out print these fruits separately because they are each a choice to a question stored in a single variable. How can I do this? The code above is my failed attempt because the substring doesn't update the str variable rather creates a new string. I can't use a loop and I can't make it dynamic and thus not use it.

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
pac bell
  • 31
  • 7
  • Check my IP adress and find out whether its a real duplicate and spam question. I doubt that question has the answer fit for my case. – pac bell Apr 03 '17 at 15:08
  • You have a string containing the words "A B O" and you ask how to print them separately. So you want to split that string by " ". That is all there is to this. And duplicating a question has **nothing** to do with who asks the question. But what the question is about. You better spend some time at the [help] to understand how things work here. And beyond that: you want us to spend our time to help you; so you please spend the 1 minute it takes to properly format/indent your input to us; instead of dropping such a mess here. – GhostCat Apr 03 '17 at 15:12
  • if you split your string by space it will return an array, in which each fruit will be an item of that array. you can just loop through that array and use it – Ashraful Islam Apr 03 '17 at 15:12

2 Answers2

0

You need to change str as well:-

while(!str.equals("") ) { 
    int a = str.indexOf(" ");
    System.out.println(str.substring(0, a));
    String sentence = str.replaceFirst(str, str.substring(a));
    System.out.println(sentence);    
    str = str.substring(a); // Remove the bit of str that we've processed.

} 

(Untested, but you get the idea). You obviously also need to check if str actually contains a space and drop out.

Steve Smith
  • 2,244
  • 2
  • 18
  • 22
0

If i understand you correctly, you should try to use StringTokenizer

StringTokenizer st=new StringTokenizer("Apple Banana Orange");

        while (st.hasMoreTokens()){
            System.out.println(st.nextToken());
        }