【发布时间】:2019-01-31 16:25:55
【问题描述】:
我正在用 Java 为学校制作一个分数计算器。我正在尝试使用数组找到最大公约数,但我不断收到错误消息,告诉我没有找到适合 add(ArrayList) 的方法。基本上我要做的是将 numbFactors arraylist 和 denFactors arraylist 添加到 bestCd数组列表。
ArrayList<Integer> numFactors = new ArrayList<>();
ArrayList<Integer> denFactors = new ArrayList<>();
ArrayList<Integer> greatestCd = new ArrayList<>();
// reduce the fraction result.
// find the factors of the numerator and denominator. check
for(int i = 2; i < rn +1; ++i){
//check if the factors go evenly. check
if (rn%i == 0){
numFactors.add(i);
}
}
//Same for denominators. check
for(int i = 2; i < rd +1; ++i){
//check if the factors go evenly. check
if (rd%i == 0){
denFactors.add(i);
}
}
//Find the greatest common divisor
//Find the common factors
for(int i =0; i < numFactors.size(); i++){
for(int j =0; j<denFactors.size(); j++){
if(numFactors == denFactors){
greatestCd.add(numFactors);
greatestCd.add(denFactors);
}
// check to see which are the same
// if they are, add them to the third arraylist
}
}
这是我遇到的错误
error: no suitable method found for add(ArrayList<Integer>)
greatestCd.add(numFactors);
^
method Collection.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method List.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method AbstractCollection.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method AbstractList.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method ArrayList.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
RodriguesP1.java:159: error: no suitable method found for add(ArrayList<Integer>)
greatestCd.add(denFactors);
^
method Collection.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method List.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method AbstractCollection.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method AbstractList.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
method ArrayList.add(Integer) is not applicable
(argument mismatch; ArrayList<Integer> cannot be converted to Integer)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors
【问题讨论】:
-
你可能想分别使用
numFactors.get(i)和denFactors.get(j) -
get 和 add 有什么区别?
-
不,我的意思是例如
greatestCd.add(numFactors.get(i));和if(numFactors.get(i) == denFactors.get(j)) -
我没有收到你的最后一个
if块
标签: java