程序只打印最后一个字母。你想把整个单词倒过来吗 import java.util.Scanner; 公共类项目2{ 公共静态void main(字符串[]args){ 扫描仪输入=新扫描仪(系统输入); 字符串字; 字符串c; int x,count,count1; System.out.println(“请输入一个单词:”); word=in.nextLine(); x=单词长度(); 对于(count=0;count

程序只打印最后一个字母。你想把整个单词倒过来吗 import java.util.Scanner; 公共类项目2{ 公共静态void main(字符串[]args){ 扫描仪输入=新扫描仪(系统输入); 字符串字; 字符串c; int x,count,count1; System.out.println(“请输入一个单词:”); word=in.nextLine(); x=单词长度(); 对于(count=0;count,java,substring,Java,Substring,将count1=x;赋值从循环中取出。打印完字母后,还要进行计数--;。您不需要循环来反转字符串 参考- 如果要反向打印字符,请忘记子字符串 Scanner in = new Scanner(System.in); System.out.println(new StringBuilder(in.nextLine()).reverse()); 直到x=word.length()为止,您都是正确的。它正在打印最后一个字符的第二个字符,因为您一直将count1的值设置为word的长度,并将其减去1。

count1=x;
赋值从循环中取出。打印完字母后,还要进行
计数--;

您不需要循环来反转字符串

参考-

如果要反向打印字符,请忘记子字符串

Scanner in = new Scanner(System.in);
System.out.println(new StringBuilder(in.nextLine()).reverse());

直到
x=word.length()
为止,您都是正确的。它正在打印最后一个字符的第二个字符,因为您一直将count1的值设置为
word
的长度,并将其减去1。因此,它一直引用最后一个字符。若要解决此问题,请执行以下操作:

String word = in.nextLine();
int x = word.length();
for(count = x - 1; count >= 0; count--) {
    System.out.println(word.charAt(count));
}
count1=x;

对于(count=0;count,如果您想通过遍历以艰难的方式完成,请执行以下更改

count1=x;
for(count=0;count<x;count++) {
    c=word.substring((count1)-1,count1);
    System.out.println(c);
    count1--;
}
更新:您可以使用
charAt#String
轻松获取某个位置的字符

for(count=x;count>=0;count--) {
   System.out.println(word.substring(count - 1,count));
}

每次循环运行时,您都会将count1值重置为x(count1=x),因此c始终是相同的值。
为了实现这一点,请尝试将count1=x从循环中取出,以便每次循环运行时,count1值都会按预期减少,从而提供所需的子字符串。

进入循环
,以便(count=0;count当您需要向后遍历时,要比向后遍历它。FWIW-那么,count1的起始值是什么呢?我怀疑这是唯一的解决办法,因为
c
在循环中一次又一次地被重新分配,从不生成反向字符串。它将在新行中打印字符串的每个字母。这不是问题的答案问题..如果要提供另一种选择,我们可以将OP定向到也许,但他们最终问了他们想知道如何将整个单词向后打印,因此您的选择…请记住接受最适合您的问题的答案,以便StackOverflow可以正确存档。
substring(count-1,count)
charAt(count)
@cricket\u 007的效果相同。谢谢您的提醒。
for(count=x;count>=0;count--) {
   System.out.println(word.substring(count - 1,count));
}
for(count=x-1;count>=0;count--) {
       System.out.println(word.charAt(count));
}
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
word=in.nextLine();
System.out.println(new StringBuilder(word).reverse());
x=word.length();
for(count= x-1; count >= 0; count--) {
    c = word.substring((count)-1, count);
    System.out.print(c);
}