Java中的字符反转
我正在学习Java编程101,我真的被这个作业困住了: “创建一个要求输入用户名并按相反顺序打印的程序。不需要为此创建单独的方法 键入你的名字:保罗 按相反顺序:luaP 键入你的名字:凯瑟琳 按相反顺序:enirehtaC“ 我不明白为什么我的代码会给出错误的结果。以下是我迄今为止的代码:Java中的字符反转,java,Java,我正在学习Java编程101,我真的被这个作业困住了: “创建一个要求输入用户名并按相反顺序打印的程序。不需要为此创建单独的方法 键入你的名字:保罗 按相反顺序:luaP 键入你的名字:凯瑟琳 按相反顺序:enirehtaC“ 我不明白为什么我的代码会给出错误的结果。以下是我迄今为止的代码: import java.util.Scanner; public class ReversingName { public static void main(String[] args) {
import java.util.Scanner;
public class ReversingName {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a name:");
String name = reader.nextLine();
int i = name.length();
while (i > 0){
char character = name.charAt(i);
System.out.print(character);
i--;
}
}
}最后一个字符不是string.length,而是string.length-1
int i = name.length() - 1; // you forgot the -1
while (i >= 0) // and the equal sign must be there because if its not you are missing the first letter
{
char character = name.charAt(i);
System.out.print(character);
i--;
}
与使用StringBuilder的
reverse()
方法相关。按相反顺序打印inti=name.length()-1;而(i>=0){…}
索引从0开始,直到.length()-1。您的程序将抛出IndexOutOfBoundsException。