2017-05-24 40 views
-5

不被显示的出界异常和我的代码仍然运行的Java不会赶上OutOfBounds异常

import java.util.*; 
import java.io.*; 

public class pr50 
{ 
    static String[] arr; 
    static int modes; 
    static int old; 
    static int[] nums; 

    public static void main(String[] args) throws IOException 
    { 
     Scanner in = new Scanner(new File("pr50.dat")); 
     int limit = in.nextInt(); 
     in.nextLine(); 
     for(int x = 0; x < limit; x++) 
     { 
     arr = in.nextLine().split(" "); 
     nums = new int[arr.length]; 
     for(int b = 0; b < arr.length; b++) 
     { 
      nums[b] = Integer.valueOf(arr[b]); 
     } 
     Arrays.sort(nums); 
     old = 0; 
     modes = 0; 
     for(int y = 0; y < nums.length; y++) 
     { 
      int current = nums[y]; 
      for(int c = 0; current == nums[y+c] && nums[y+c] < nums.length ; c++) 
      { 
       if(old < 1) 
        modes++; 
       else 
        old++; 
       current = nums[y+x]; 
      } 
     } 
     if(modes > 1) 
      System.out.println(modes + " MODES"); 
     else 
      System.out.println(modes + " MODE"); 
     } 
    } 
} 

下面是一个示例文件:

2 
56 77 66 22 33 55 66 66 66 
80 93 87 72 80 77 43 87 98 99 100 
+2

是的。这是一些代码好吧。那么你认为问题在哪里? – John3136

+0

如果它运行,那么没有例外。给出实际引发异常的示例输入 –

+0

在循环的第二次迭代中,current == nums [y + c]将为false,并且for循环将终止。将不会抛出OOB异常。 –

回答

1

的错误是在这里:

for(int c = 0; current == nums[y+c] && nums[y+c] < nums.length ; c++) 

想一想,如果nums [y + c] 意味着nums [y],循环将至少运行一次nums.length但如果你的阵列中,最大的因素是大于或等于数组的长度,它永远不会考虑nums[y+1],让我们尝试:

1 
1 2 3  //lenght = 3 
2 MODES 

因为最大的元素,3 < 3是失败,它不会在下一时间循环中运行nums[y+1],但如果键入:

1 
1 1 1 1 1 1 1 //lenght = 7 

最后一个元素是1和1 < 7,环路将运行下一个循环,并检查NUMS [6 + 1]

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 

所以为了使它出现OutOfBoundsException,最大的元素必须小于行的长度(平均元素数)!

run: 
1 
0 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
    at test.main(test.java:30) 
C:\Users\Fes Nguyen\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 
BUILD FAILED (total time: 2 seconds) 
+0

对不起,因为我必须编辑我的答案很多时间:D,我是新手! –

相关问题