我目前正在创建一个程序,用户输入一个整数数组。该程序必须找到连续元素的最长增加函数。因此,如果用户输入" 3,2,1,2,4,6,7,8,1,2"该程序将输出" 1,2,4,5,6,7,8"。但是,我一直遇到错误。首先,它不会输出最后一个元素(在这种情况下,8)...所以我添加了"(xs [i + 1]> xs [i])"条件。但是,现在当我运行它时,它会在线程" main"中出现"异常。 java.lang.ArrayIndexOutOfBoundsException:-1"错误。任何帮助,将不胜感激。
public class average1{
static int[] increasing(int[] xs){
int[] best_array = new int[xs.length];
int[] current_array = new int[xs.length];
int b_counter = 0;
int c_counter = 0;
for (int i = 0; i<xs.length; i++){
if ((xs[i] > xs[i-1]) || (xs[i+1] > xs[i])){
current_array[c_counter] = xs[i];
c_counter++;
} else {
if (c_counter>b_counter){
for (int j=0; j<(c_counter+1); j++){
best_array[j] = current_array[j];
current_array[j] = 0;
}
b_counter = c_counter;
c_counter = 0;
}
}
}
int[] out_array = new int[b_counter];
for (int k=0; k<(b_counter); k++){
out_array[k] = best_array[k];
}
return out_array;
}
public static void main(String[] args) {
System.out.println("Enter how many strings you'd like to store: ");
Scanner user_input = new Scanner(System.in);
int num_of_strings = Integer.parseInt(user_input.nextLine());
int[] array_of_strings = new int[num_of_strings];
for (int i = 0; i < array_of_strings.length; i++){
System.out.println("Enter the string " + (i+1) + " : ");
array_of_strings[i] = Integer.parseInt(user_input.nextLine());
}
System.out.println(Arrays.toString(increasing(array_of_strings)));
}
}
编辑:我已经查看了其他主题并且仍然没有得到它,有人可以解释一下吗