Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
int factors1 = 0;
         int factors12 = 0;
         StringBuilder sb = new StringBuilder();
         String value = edtCommonFact.getText().toString()
             String[] stringsNumber = value.split(",");
             Integer[] integersNumbers = new Integer[stringsNumber.length];
             for (int i = 0; i<stringsNumber.length; i++){
                 integersNumbers[i] = Integer.parseInt(stringsNumber[i]);
             }
             Arrays.sort(integersNumbers);
             for (int i = 1; i<=integersNumbers[0]; i++){
                 if (integersNumbers[0]%i == 0){
                     factors1 = i;
                     sb.append(factors1).append(" ");
              for (int j = 1; j<=integersNumbers.length; j++){
                  if (integersNumbers[j]%j == 0){
                      factors12 = j;
                      sb.append(factors12).append(" ");
                  }
              }
                     }

             }
        String result = sb.toString();
         commonFactResult.setText("Common factors are: " + result);


What I have tried:

This line throws the exception.
if (integersNumbers[j]%j == 0){
Posted
Updated 27-Aug-21 22:43pm

1 solution

Take off the equals sign, and probably start from zero instead of one.
for (int j = 1; j<=integersNumbers.length; j++){
Should probably be:
for (int j = 0; j < integersNumbers.length; j++){
Arrays in Java start from zero and the last index is the number of elements minus one.
So for an array with 3 elements, the valid indexes are 0, 1, and 2 - any other values will give an error.
The loop above that is probably wrong as well (along with being very odd looking code ...)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900