I'm trying to do the below tutorial question.
// Create a method called greatestCommonFactor
// It should return the greatest common factor
// between two numbers.
//
// Examples of greatestCommonFactor:
// greatestCommonFactor(6, 4) // returns 2
// greatestCommonFactor(7, 9) // returns 1
// greatestCommonFactor(20, 30) // returns 10
//
// Hint: start a counter from 1 and try to divide both
// numbers by the counter. If the remainder of both divisions
// is 0, then the counter is a common factor. Continue incrementing
// the counter to find the greatest common factor. Use a while loop
// to increment the counter.
And my code is below
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Ex4_GreatestCommonFactor {
// This is the main method that is executed as
// soon as the program starts.
public static void main(String[] args) {
// Call the greatestCommonFactor method a few times and print the results
}
public static int greatestCommonFactor(int a, int b){
int i = 1 ;
while (i >= 1 ){
i++;
}
if (a%i == 0 && b%i == 0){
ArrayList factor = new ArrayList<Integer>();
factor.add(i);
}
else if (a%i <= 1 || b%i <= 1){
Collections.sort(factor);
List<Integer> topnum = factor.subList(factor.size() - 1, factor.size());
}
return topnum;
}
}
So I have 2 questions.
1) In my elseif statement, I get an error where factor
cannot be resolved to a variable. How do I "carry over" the factor
ArrayList from the previous If statement into this elseif statement?
2) I also get a similar error where topnum
cannot be resolved. Is this also a placement error for this line of code in my method, or am I making a completely different mistake?
Aucun commentaire:
Enregistrer un commentaire