递归方法中的 ArrayIndexOutOfBoundsException 错误



我正在尝试创建一个从用户那里获取int t和String s的程序。字符串 s 将在空格处拆分并放入 String[] 字符串中。当 t=1 时,main 方法打印字符串,在方法反向中使用递归反转其元素,该方法采用两个整数(末端的索引(和一个字符串数组,然后打印反转的字符串数组。下面的代码编译没有问题,但是当我按回车键输入 1 表示 t 时,我立即收到 ArrayIndexOutOfBounds 错误。错误引用了第 11 行和第 34 行,但我挠头,因为我看不出任何错误。

import java.util.Scanner;
public class Recursion
{
public static String[] reverse(int m, int n, String[] str)
{
String[] p = new String[str.length];
if (m == n) return str;
else if (m > n) return str;
else
{
str[m] = p[n];
str[n] = p[m];
return reverse(m+1, n-1, str);
}
}
public static void main(String[] args)
{
Scanner enter = new Scanner(System.in);
System.out.print("t = ");
int t = enter.nextInt();
System.out.print("s = ");
String str = enter.nextLine();
String[] Strings = str.split(" ");
int k = Strings.length;
if (t == 1)
{
for (String s : Strings)
System.out.println(s);
System.out.println("The reversal is");
reverse(k-k, k, Strings);
for (String s : Strings)
System.out.println(s);
}
}
}

java 中的数组从 0 开始到长度 -1

有关更多详细信息,请参阅数组。

所以传递 k 会抛出ArrayIndexOutOfBounds使用以下代码

reverse(0, k-1, Strings);

最新更新