0

我制作了一个程序来反转输入字符串的单词有一个错误代码:

                   Exception in thread "main" java.lang.StringIndexOutOfBoundsException:String index out of range: 17
                   at java.lang.String.charAt(String.java:695)
                   at Rev.main(Rev.java:14)

主程序代码为:

import java.io.*;
class Rev
{
 public static void main(String args[])throws IOException
  {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter String");
    String a=br.readLine();
    a=" "+a+" ";
    int x=a.length();
    String b;
    for(int z=a.length()-1;z>=0;z--)
    {
     if (a.charAt(z)==' ')
     {
      b=a.substring(z,x);
      System.out.print(b+" ");    
      a=a.replace(b,"");
     }
    }
  }

}

4

5 回答 5

1

如果 Java 专业人士需要解决您的问题,他只需几行代码即可完成:

final List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
for (String word : words) System.out.print(word + " ");
System.out.println();

如果您将此作为练习并想自己实现,您仍然可以考虑使用相同的基本思想。例如,遍历您的字符串并将空格的所有位置收集到List<Integer>. 然后使用input.substring(list.get(i), list.get(i-1)).

于 2012-10-12T17:22:01.957 回答
0

You know the string index you're specifying is wrong. You know where the error's occurring. Add System.out.println calls to print the sting index and the length of the string just before the errant statement, and at other critical points in your code. Debug the problem.

于 2012-10-12T17:15:31.303 回答
0

也许你应该尝试:

int x=a.length()-1;

子字符串导致错误

于 2012-10-12T17:12:20.870 回答
0

为什么不将输入按空间拆分并存储在数组中并反转数组?

于 2012-10-12T17:12:25.370 回答
0

好吧,我知道这不是您问题的答案,但是您为什么不尝试 StringBuilder 或 StringBuffer 方法,称为 reverse()

StringBuilder sb = new StringBuilder("Hello");

sb.reverse();
于 2012-10-12T17:20:51.720 回答