java - 如何在java中使用while循环反转字符串?

标签 java string while-loop

我有一个任务,我需要让代码接受用户输入的单词,将其变成大写字母,反转并输出它。到目前为止,这是我的代码,但我真的不知道如何做到这一点。

import java.util.Scanner;

public class WordSizeChecker {

    public static void main(String[] args) {
        Scanner kb = new Scanner (System.in);
        System.out.print("Please enter a word: ");
        String oword = kb.nextLine();
        String word = oword.toUpperCase();
        int length = word.length();
        int i = 0;
        while (i < length)
        {
            System.out.println(word.substring(i,length));
            length--;
        }

    }

}

输出:

Please enter a word: chess
CHESS
CHES
CHE
CH
C

最佳答案

new StringBuilder(oword).reverse().toString().toUpperCase();

或者使用循环

oword = oword.toUpperCase();
for(int i = oword.length() - 1; i >= 0; i--)
{
    System.out.print(oword.charAt(i));
}
System.out.println();

关于java - 如何在java中使用while循环反转字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247768/

相关文章:

java - 在客户端和服务器之间以字节数组形式发送图像

regex - Python 3.3 中查找字符串是否以\U 开头

arrays - Swift - 替换多个数组中数组的重复字符串

c++ - 使用 while 循环和 for 循环排序?

java - jQuery ajax 调用不适用于自签名证书

java - 如何从字符串中删除 "¼"和 "½"

java - CDI Bean 中的默认拦截器

ios - 应用程序不在标签上显示 var 字符串

c - while 循环中的 scanf 仅适用于第一次迭代

python - 当 for 循环的变量有一段时间条件时,如何在 for 循环中获得步骤跳转