2014-02-24 41 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的數組,條目編號爲0,1和2。如果您嘗試使用進入3號,你會得到異常。但這正是你正在做的 - 所有的循環都會持續到i = 2(包括那種情況),但是你繼續嘗試使用數組的條目i + 1

相關問題