ArrayLists
。ArrayLists
中的每个元素和多个值相加,并将答案存储在第三个ArrayList
中。例如:ListA[0] * ListB[0] = ListC[0]
我创建并填充了第一个列表,但是计算方法extend
让我失望。我所拥有的代码如下所示。任何人都可以提供有关我在这里缺少什么的见解吗?
package threeArrayLists;
import java.util.ArrayList;
public class ThreeArrayLists {
public static void main(String[] args) {
double [] price_Array = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98};
double [] quantity_Array = {4.0, 8.5, 6.0, 7.35, 9.0, 15.3, 3.0, 5.4, 2.9, 4.8};
ArrayList<Double> priceList = new ArrayList<Double>();
ArrayList<Double> quantityList = new ArrayList<Double>();
ArrayList<Double> amountList = new ArrayList<Double>();
for (int i = 0; i < price_Array.length; i++) {
priceList.add(price_Array[i]);
}
for (int j = 0; j < quantity_Array.length; j++) {
quantityList.add(quantity_Array[j]);
}
extend(priceList, quantityList, amountList);
}
private static void extend(ArrayList<Double> prices,
ArrayList<Double> quantity,
ArrayList<Double> amount) {
for (int k = 0; k < prices.size() && k < quantity.size(); k++) {
amount.add(prices[k] * quantity[k]);
}
}
}
答案 0 :(得分:2)
你真的需要名单吗?从您帖子中的代码来看,这一点尚不清楚, 并且没有明显的理由使用列表。 通过仅使用数组,实现可以更短更简单:
public static void main(String[] args) {
double[] priceArray = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98};
double[] quantityArray = {4.0, 8.5, 6.0, 7.35, 9.0, 15.3, 3.0, 5.4, 2.9, 4.8};
double[] amountArray = multiply(priceArray, quantityArray);
}
private static double[] multiply(double[] prices, double[] quantity) {
double[] result = new double[prices.length + quantity.length];
for (int k = 0; k < prices.length && k < quantity.length; k++) {
result[k] = prices[k] * quantity[k];
}
return result;
}
如果你真的想使用列表:
public static void main(String[] args) {
Double[] priceArray = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98};
Double[] quantityArray = {4.0, 8.5, 6.0, 7.35, 9.0, 15.3, 3.0, 5.4, 2.9, 4.8};
List<Double> priceList = Arrays.asList(priceArray);
List<Double> quantityList = Arrays.asList(quantityArray);
List<Double> amountList = multiply(priceList, quantityList);
}
private static List<Double> multiply(List<Double> prices, List<Double> quantity) {
List<Double> result = new ArrayList<Double>();
for (int k = 0; k < prices.size() && k < quantity.size(); k++) {
result.add(prices.get(k) * quantity.get(k));
}
return result;
}
注意:
List<Double>
而不是ArrayList<Double>
camelCase
,没有下划线(没有_
个字符)double[]
更改为Double[]
,您可以使用Arrays.asList
轻松将其转换为列表,就像我在上面的示例中所做的那样答案 1 :(得分:0)
您使用extend
时未使用ArrayList
中的数组。那么,你要找的是.get
:
private static void extend(ArrayList<Double> prices, ArrayList<Double> quantity, ArrayList<Double> amount) {
for (int k = 0; k < prices.size() && k < quantity.size(); k++) {
amount.add(prices.get(k) * quantity.get(k));
}
}
答案 2 :(得分:0)
prices
和quantity
不是数组,它们是ArrayList
。他们不支持[]
运算符,但您可以使用get(int)
方法访问其元素:
for(int k = 0; k < prices.size() && k < quantity.size(); k++)
{
amount.add(prices.get(k) * quantity.get(k));
}