2014-02-24 5 views
-2

나는 초보자이며 여기에 내 코드가 무엇이 잘못되었는지 전혀 모른다. 질문과 코드를 여기에 작성하겠습니다. 누구든지 나를 도울 수 있으면 제발. 질문에 : 주어진 시간에 수행 할 수있는 총 잡일 수를 말해야합니다. 첫 번째 입력은 사용자가 얻은 총 시간입니다. 두 번째 입력은 사용자가 수행하려는 총 잡일입니다. 마지막 입력은 각 작업을 완료하는 데 걸리는 시간입니다.스레드 "main"예외를 해결하는 방법 java.lang.ArrayIndexOutOfBoundsException : 3

여기 내 코드 진행됩니다

공공 정적 무효 메인 (문자열 []에 args) { 스캐너 스캔 = 새로운 스캐너 (System.in)를;

int totalmins, chores=0, eachtime, totalchores, counter=0; 


    // getting the input 
    System.out.println("Enter the total time:"); 
    totalmins=scan.nextInt(); 
    while (totalmins>100000) { 
     System.out.println("Enter again. Less than 100000:"); 
     totalmins=scan.nextInt(); 
    } 

    System.out.println("Enter the total chores:"); 
    chores=scan.nextInt(); 

    int [] time = new int[chores]; 

    for (int i=1; i<chores; i++) { 
     System.out.println("Enter time:"); 
     eachtime=scan.nextInt(); 
     time[i]=eachtime; 
    } 
    // arranging in ascending order 
    for (int i=0;i<time.length; i++) { 
     if (time[i] > time[i+1]) { 
      int temp = time[i]; 
      time[i]=time[i+1]; 
      time[i+1]=temp; 
     } 

     } 
     for (int i=0;i<time.length; i++) { 
      totalchores=time[i] + time[i+1]; 
      counter++; 

      if (totalchores>totalmins) { 
       counter=counter-1; 
       System.out.println(counter); 
      } 
     } 
    } 
+4

짐작할 수 있다면, 오류 (java.lang.ArrayIndexOutOfBoundsException')가 무엇이라고 생각하십니까? –

+0

배열에 대한 내 for 루프 카운터가 문제를주고 있다고 생각하십니까? – user3345066

+0

for 루프에서 -1을 시도하십시오. 아니면 베이글을 먹어라. – TastyLemons

답변

0

나는 당신이 그 예외를 얻을 것이다, 당신이 놓치고있는 점은 당신이 항목 번호 3를 사용하려고하면 길이 3의 배열에서 항목은 0, 1, 2를 번호가 있다고 생각 . 하지만 그게 바로 당신이하고있는 일입니다. 모든 루프는 i = 2 (그 경우 포함)까지 계속됩니다.하지만 배열의 i + 1 항목을 사용하려고합니다.

관련 문제