-1

The question for homework is the program should print the String in reverse word by word.
Your `String' should be assigned the value “pay no attention to that man behind the curtain” and should be printed as the sample output.

Getting errors compiling and been at this for 3 hours - lost!!

I must use the charAt method, the substring method and an if statement:

curtain
the
behind
man
that
to
attention
no
pay

public class backwards
{
    public static void main(String args[])
    {
        String s1 = new String("pay no attention to that man behind the curtain");

        /*int pos = s1.indexOf(' ');
        while(s1.length() >  0)
        {
            if(pos == -1)
            {
                System.out.println(s1);
                s1 = "";

            }
            else
            {
                System.out.println(s1.substring(0,pos));
                s1 = s1.substring(pos+1);
                pos = s1.indexOf(' ');
            }

        }*/
        int pos = 0;
        for(int i = s1.length()-1 ; i >= 0; i--)
        {
        //  System.out.println("Pos: " + pos);
            if(s1.charAt(i) == ' ')
            {
                System.out.println(s1.substring(i+1));
                s1 = s1.substring(0,i);
            }
            else if(i == 0)
            {
                System.out.println(s1);
                s1 = "";
            }
        }
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Topps
  • 19
  • 4

1 Answers1

3

You can do it simply as

public class Main {
    public static void main(String[] args) {
        // Split on whitespace
        String[] arr = "pay no attention to that man behind the curtain".split("\\s+");

        // Print the array in reverse order
        for (int i = arr.length - 1; i >= 0; i--) {
            System.out.println(arr[i]);
        }
    }
}

Output:

curtain
the
behind
man
that
to
attention
no
pay

Alternatively,

public class Main {
    public static void main(String[] args) {
        String s1 = "pay no attention to that man behind the curtain";
        for (int i = s1.length() - 1; i >= 0; i--) {
            if (s1.charAt(i) == ' ') {
                // Print the last word of `s1`
                System.out.println(s1.substring(i + 1));

                // Drop off the last word and assign the remaining string to `s1`
                s1 = s1.substring(0, i);
            } else if (i == 0) {
                // If `s1` has just one word remaining
                System.out.println(s1);
            }
        }
    }
}

Output:

curtain
the
behind
man
that
to
attention
no
pay
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110