微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用Java反转句子

如何解决用Java反转句子

家庭作业的问题是程序应逐字逐字打印String
应该为您的“字符串”分配值“不要在窗帘后面注意那个人” ,并应将其打印为示例输出

编译时出错,并花了3个小时-迷路了!

我必须使用charat方法substring方法if语句:

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

解决方法

您可以简单地这样做

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]);
        }
    }
}

输出:

curtain
the
behind
man
that
to
attention
no
pay

或者,

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);
            }
        }
    }
}

输出:

curtain
the
behind
man
that
to
attention
no
pay

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。