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 = "";
}
}
}
}