【发布时间】:2017-04-03 21:26:06
【问题描述】:
通过调用填充遍历 (b) 中创建的 ArrayList,反转存储在 ArrayList 中的每个数字的符号。提示:使用调用来获取和设置 Arraylist 的方法。使用调用 get(int index) 和 set(int index, E element)。如有必要,方法 remove(int index) 会很方便。
输出存储在创建和操作的 ArrayList 中的所有值。 5 个值 每行
我被困在这部分,我不知道下一步该做什么。如果有人可以帮助我,将不胜感激。
这就是我的代码的样子
public class ArrayListPratice {
public static ArrayList populate(){
ArrayList a = new ArrayList();
for (int i = 0; i<100+(int)(Math.random()*100); i++)
a.add(Math.random()*100-50);
return a;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = -1;
ArrayList <Integer> c = new ArrayList <>();
while (a != 0){
System.out.print("Please enter an integer: ");
a = keyboard.nextInt();
if (a !=0){
c.add(a);
}
}
int sum = 0;
int value = c.size();
double avg = 0;
for (int i = 0; i < value; i++){
sum += c.get(i);
}
avg= (double)sum/value;
System.out.println("");
System.out.println("Sum of the values: " + sum);
System.out.println("Amount of values: " + value);
System.out.println("Average: " + avg);
ArrayList b = populate();
for (int i = 0; i < a; i++) {
c.get(i);
c.set(i, value);
}
【问题讨论】:
-
似乎指令要求您使用
get()检索每个索引处的元素,并使用set()将符号反转值存储在同一索引处。由于您使用的是ArrayList的原始版本(淘气!),您必须将 List 元素的类型转换为有用的东西。Math.random()返回double,因此您的 List 元素应该属于该类型的包装类Double。