Give one point to A[i] if either A[i]%A[j] ==0 or A[j]%A[i] == 0 Calculating the total points received by every element. Input: A={2,3,4,5,6} Output: 2,1,1,0,2 I am getting this error message: Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.main(Main.java:29)
class Main { public static void main(String args[]) { ArrayList<Integer> al = new ArrayList<>(); al.add(2); al.add(3); al.add(4); al.add(5); al.add(6); int c=al.size()-1; while(c>=0){ int count=0; for (int i=0; i<al.size(); i++){ if(i==c){ break; } else{ if(al.get(c)>al.get(i)){ if(al.get(c)%al.get(i) == 0){ count++; } } else{ if(al.get(i)%al.get(c) == 0){ count++; } } } } al.set(1,count); --c; } for(int i : al){ System.out.print(i); } } }
Advertisement
Answer
When you are running the code, this line:
al.set(1,count);
Can set count = 0. So when the value at slot 1 will be used, it will throw the error.
For “where is the error”, java has pretty error informations, and it will return something like:
Exception in thread "main" java.lang.ArithmeticException: / by zero at com.me.myprogram.MainClass.main(MainClass.java:61)
And you will see that the line 61 is:
if(al.get(c) % al.get(i) == 0){
I suggest you to check when it’s 0, or to don’t set 0 count like check if it’s 0, and set 1, for example:
if(count != 0) { al.set(1, count); // here the value will change only if we could use it after } /* With this part, it will change the value but also preventing all issue with /0 else { al.set(1, 1); } */