数组索引越界

Array index out of bounds

虽然我尝试使用 break 解决异常,但在输入“321”时仍然失败。 hackerrank 上冒泡排序的代码。

错误发生在if(a[i+1]==n)

import java.io.*;``
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] a = new int[n];
    for(int a_i=0; a_i < n; a_i++){
        a[a_i] = in.nextInt();
    }
    // Write Your Code Here
    int numSwaps=0;
    for(int i=0;i<n;i++){
        if(a[i+1]==n){       // error occurs here
            break;
        }
        else{
                if(a[i]>a[i+1]){
                int temp=a[i];
                a[i]=a[i+1];
                a[i+1]=temp;
                numSwaps++;
                }
            }
    }
    //firstElement=a[0];
    //lastElement=a[n-1];
    System.out.println("Array is sorted in"+" "+numSwaps+" "+"swaps."+"\n"+"First Element:"+" "+a[0]+"\n"+"Last Element:"+" "+a[n-1]);
}

}

你的条件i<n会在i=n-1时溢出,因为你在添加i+1,你引用数组越界

修复很简单,但是,将条件更改为 i<n-1

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        // Write Your Code Here
        int numSwaps=0;
        for(int i=0;i<n-1;i++){
            if(a[i+1]==n){
                break;
            } else if(a[i]>a[i+1]){
                int temp=a[i];
                a[i]=a[i+1];
                a[i+1]=temp;
                numSwaps++;
            }
        }
        //firstElement=a[0];
        //lastElement=a[n-1];
        System.out.println("Array is sorted in"+" "+numSwaps+" "+"swaps."+"\n"+"First Element:"+" "+a[0]+"\n"+"Last Element:"+" "+a[n-1]);
}

此外,对代码风格感到自豪;我做了几次润色,但还远未 干净。

只需将for循环中的条件更改为I < n- 1,这是由于您程序中的交换模块中的I+1..