试图逆转字符串输入。
eg: 输入 - 你好朋友 输出 - dneirf olleh
这是我制作的程序,但它显示出字符串索引范围为错误:
import java.io.*;
class Worksheet3sum3
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
System.out.print("enter string ");
String S=br.readLine();
String y=" ";
for(i=0;i<=S.length();i++)
{
char ch=S.charAt(i);
y=ch+y;
}
System.out.print("the reverse is "+y);
}
}
是因为您超越了字符串的最后一个索引,原因是我们始终在0开始计数,所以在这种情况下,您打算说
i < S.length()
。
for(i=0;i<=S.length();i++) // this is why it's saying index out of bounds because you're going 1 index beyond the last.
{
char ch=S.charAt(i);
y=ch+y;
}
以下解决方案应解决您的" indexoutofbounds"问题:
for(i=0;i< S.length();i++) // notice the "i < S.length() "
{
char ch=S.charAt(i);
y=ch+y;
}
另外,我想提供一种简单简便的算法,您可以用来实现相同的结果。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter string ");
String value = scanner.nextLine();
StringBuilder builder = new StringBuilder(value); // mutable string
System.out.println("reversed value: " + builder.reverse()); // output result
}
update
当您要求我扩展您为什么会遇到indexoutofbounds错误的问题时,我将在下面提供演示。
假设我们现在有一个变量String var = "Hello";
,因为您可以看到该变量内有5个字符,但是,我们开始计数为0,而不是1个字符,而不是1 so" h"是index 0," e"是index 1,"索引2等等,最终,如果您要访问最后一个元素,即使我们在字符串变量中有5个字符,也是索引4。因此,提及您的问题的原因是它说界限的索引是因为您要高出最后一个索引。这是有关问题的进一步说明和练习的链接。
使用子字符串,您可以通过要向后打印的字符串循环,然后向后打印字符串的字符。
您也可以使用命令.toCharArray()
,然后通过字符阵列向后循环以向后打印单词。