import java.io.*;
public class Program
{
public static void main(String args[])throws IOException
{
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (isr);
int i, len;
char ch;
String rev = "";
System.out.println("Enter a String:");
String str = br.readLine();
len = str.length();
for(i=len; i>=0; i--)
{
ch = str.charAt(i);
rev = rev + ch;
}
System.out.println("Reversed String is: " +rev);
}
}
该程序正常工作,直到输入后按Enter键。 例如 输入字符串:
的java
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at Program.main(Program.java:16)
Java Result: 1
我尝试在NetBeans中编译它。请解释一下。
答案 0 :(得分:1)
使用for(i=len-1; i>=0; i--)
而非for(i=len; i>=0; i--)
,否则str.charAt(i)
将在for循环的第一次迭代中超出字符串的最后一个字符。
String str = "ABCDE"; // for example
int len = str.length(); // 5
"ABCDE" (your string)
01234 (index)
str.charAt(0) // 'A'
str.charAt(len-1) // 'E'
str.charAt(len) // StringIndexOutOfBoundsException occurs
答案 1 :(得分:0)
请考虑使用StringBuffer的reverse()方法:
import java.io.*;
public class Program
{
public static void main(String args[]) throws IOException
{
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (isr);
System.out.println("Enter a String:");
StringBuffer sbInput = new StringBuffer(br.realLine());
System.out.println("Reversed String is : " + sbInput.reverse());
}
}