不要问我为什么在java中获取数组的索引越界错误



我正在解决学校级别的问题"查找数组中最大的项目">

这是代码

package geeksforgeeks;
import java.util.Scanner;
public 
class LargestElementInArray {
public static void main(String[] args) {
int temp;  
//varible used for sorting
int tempJ; 
//varible used for swapping
int a[] = {5,5,2,3,5,2,6,23,25,23,5,355,333,3,15,15,25};
//array of whcih we will find the largest element    
// array.length does not give the index value it just gives the normal counting so i subtracted 
// 1 from the length to get the index length
int arrayLength =  a.length - 1;
System.out.println(arrayLength);
//sorting starts
for(int i = 0; i < arrayLength; i++){
for(int j = 0; j < arrayLength ; j++){
tempJ = j + 1;
System.out.println(tempJ);
if(a[j] > a[tempJ])
//if the right element is smaller than it would swap their places using their index
// i don't think i need to provide how it is working it is really basic code               
{
temp = a[j];
a[j] = a[i++];
a[i++] = temp;
}
}
}
//Printing the largest item present at the end of the array
System.out.println(a[arrayLength);
}
}

我对数组进行了排序,并打印了最大的元素,该元素将在排序后位于数组的最后

现在出现了一个错误,我不知道为什么我会得到

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 17 out of bounds for length 17
at geeksforgeeks/geeksforgeeks.LargestElementInArray.main(LargestElementInArray.java:32)

请在下面回答我为什么会出现此错误提前感谢

您的代码没有正确处理索引的范围。不需要保留用于交换的变量tempj。我们可以用逻辑来处理。

这将整理出你的问题,并给出最大的数字。

public static void main(String[] args) {
int a[] = {5,5,2,3,5,2,6,23,25,23,5,355,333,3,15,15,25};
int arrayLength = a.length;
int temp;
for (int i = 0; i < arrayLength; i++) {
for (int j = i+1; j < (arrayLength - i); j++) {
if (a[j - 1] > a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
//Printing the largest item present at the end of the array
System.out.println(a[arrayLength-1]);
}

最新更新