【发布时间】:2011-04-07 21:16:20
【问题描述】:
你好,我在编写这段代码时遇到了困难,我迷失了最后两种方法。这是一个学习练习(不是家庭作业),但我需要例子来学习。 另外,我认为这在 stackoverflow 数据库中也很有用。
public class NumberList {
public int[] values;
public NumberList() {
values = new int[0];
}
public NumberList(int[] a) {
values = new int [a.length];
for (int i=0;i<a.length;i++)
values[i] = a[i];
}
public int getSize() {
return this.values.length;
}
public int getAt(int index) {
if (index>=values.length){
throw new IndexOutOfBoundsException ("Values of out of bounds");
}else{
return values[index];
}
}
public long getTotal() {
long sum = 0;
for (int i=0; i<values.length; i++) {
sum = sum + values[i];
}
return sum;
}
// need help here its a boolean that the number is in the array but if not its //false
public boolean contains(int number) {
for (int i=0; i<values.length; i++){
if (number <values.length+1){
return true;
}
//else
// return false;
// }
// this is an add method that confuses me and ask myself why since i added without it.
public void add(int number) {
number=0;
}
}
【问题讨论】:
-
你实际上并没有问任何问题。问题是添加方法吗?应该怎么做,给数组添加新索引?
-
您能否给出一组输入以及它们的预期输出是什么?
-
您不需要检查数组边界,Java 会为您执行此操作并引发相同的异常,除非您可能想要您的消息而不是默认消息。
-
看看System.arrayCopy()
-
其实这个好像是这个的副本:stackoverflow.com/questions/5573534/…