2015-02-03 3 views
0
import java.util.*; 

public class bubblesort { 
     public int input; 
     public int c; 
     public int d; 
     public int swap; 
     public int[] arr= new int[input]; 
     Random rand = new Random(); 
     Scanner in = new Scanner(System.in); 

    public static void main(String[] args) { 
     bubblesort b = new bubblesort(); 
     Scanner in = new Scanner(System.in); 
     System.out.println("Ascending(1),Descending(2),Random(3)"); 
     int arrayInput= in.nextInt(); 

     if (arrayInput == 1) { 
      b.ascending(args); 
      } 
     else if (arrayInput == 2) { 
      b.descending(args); 
      } 
     else if (arrayInput == 3) { 
      b.random(args); 
      }   
    } 


    public void ascending(String[] args){ 
     this.input = Integer.parseInt(args[0]); 

     for (c = 0; c < input; c++){ 
      arr[c] = rand.nextInt(Integer.MAX_VALUE); 
      } 

     for (c = 0; c < (input - 1); c++) { 
      for (d = 0; d < input - c - 1; d++) { 
      if (arr[d] > arr[d+1]){ 
        swap  = arr[d]; 
        arr[d] = arr[d+1]; 
        arr[d+1] = swap; 
       } 
      } 
     } 
     for (c = 0; c < input; c++) 
     System.out.println(arr[c]); 

     long startTime = System.nanoTime(); 
     for (c = 0; c < input - 1; c++){ 
      for (d =0; d < input - c -1 ; d++){ 
       if (arr[d] > arr[d+1]){ 
        swap = arr[d]; 
        arr[d] = arr[d+1]; 
        arr[d+1] = swap; 
        } 
       } 
      } 
     long endTime = System.nanoTime(); 
     long estimatedTime = endTime - startTime; 
     System.out.println("Sorted list of numbers"); 
     for (c = 0; c < input; c++) 
     System.out.println(arr[c]); 
     System.out.println("The time it takes to sort an descending array into an ascending array is "+estimatedTime+" nano seconds"); 
     } 
    } 

그래서 그 그냥은 예외를 제공합니다명령 줄 인수가 "주"스레드에서 예외를 일으키는

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 
    at bubblesort.ascending(bubblesort.java:61) 
    at bubblesort.main(bubblesort.java:23) 

내가 생각하기에 문제는 배열 길이가 "input"이라고 불리는 것이 명령 줄 인수로 변경되지 않으므로 입력이 0으로 유지된다는 것입니다. 그렇다면이 문제를 어떻게 해결할 수 있습니까?

+2

당신의 didnt는'input'에 어떤 값도 지정하지 않으므로 0이고 길이가 0 인 배열'arr'을 생성했습니다.'arr'을 사용하고 싶다면 변수'c보다 큰 값을 할당해야합니다 '및'd' – haifzhan

+0

IDE의 중단 점 및 디버깅 기능을 사용해야합니다. ArrayIndexOutOfBoundsException을 사냥 할 때 코드에 들어가서 배열의 길이를 볼 수 있다는 것은 매우 중요합니다. – Celeo

답변

2

사용자 입력을 구문 분석하기 전에 arr을 초기화 할 수 없습니다. 문 public int[] arr= new int[input];의 결과는 배열의 크기가 0이므로 액세스하려고 시도하면 예외가 발생합니다. 배열 길이를 파싱 한 후에 메인 안의 배열을 초기화 해보십시오.

1

변수가있는 맨 위.

public int input; //NOT INITIALIZED 
public int[] arr= new int[input]; 

배열을 만들려고하기 전에 입력이 초기화되지 않았습니다. 그래서 크기가 없습니다.

main 함수 내부의 사용자 입력으로 초기화하고 배열을 생성 해보십시오.

int arrayInput= in.nextInt(); 
arr = new int[arrayInput]; 
관련 문제