问题描述
我有阵列。我有一个 isFull
方法,该方法检查数组是否已满,但是我不知道如何使用它来检查它是否已满,然后检查它是否未满。
I've got array. I've got an isFull
method, which checks if the array is full, but I don't know how to use this to check if it's full, then if it's not full add to the array, otherwise disregard the add call.
该数组应该包含10个元素,然后不再接受。在10个元素之后,它应该已满,而忽略任何 addSpy
调用。
The array should take 10 elements and then not accept any more. After 10 elements, it should 'be full' and disregard any addSpy
calls.
您将如何实现呢?
public class ConcreteSubject extends AbstractSubject {
public int arySize;
private int i = 0;
private static AbstractSpy[] spies;
public ConcreteSubject(int a) {
arySize = a;
spies = new AbstractSpy[a];
}
@Override
public void addSpy(AbstractSpy spy) {
if (spies.length < 10) {
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
public void isFull() {
//1
boolean b = false;
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
b = true;
}
}
if (!b) {
System.out.println("Array is full");
} else {
System.out.println("Array not full");
}
}
public class TestSpies {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject(10);
AbstractSpy spy = new ConcreteSpy();
AbstractSpy[] spies = new AbstractSpy[10];
cs.addSpy(spy);
cs.addSpy(spy);
cs.addSpy(spy);
cs.isFull();
}
}
推荐答案
-
spies.length< 10
是不正确的。它应该是spies.length> 0&&我< spies.length
以确保以下赋值spies [i] = spy;
始终有效。
spies.length < 10
isn't correct. It should bespies.length > 0 && i < spies.length
to make sure that the following assignmentspies[i] = spy;
is always valid.
void isFull()
应该为 boolean isFull()
。您的实现看起来不错,只需返回 b
。 full
是一个棘手的词,因为从技术上讲,数组始终是 full的。更好的形容词应该是填充
,填充
。
void isFull()
should be boolean isFull()
. Your implementation looks OK, just return b
. full
is a tricky word because technically an array is always "full". A better adjective would be populated
, filled
.
由于 addSpy
不会填补空白,而只是在末尾添加一个间谍, isFull
可以重写为 return spies.length == i;
。
Since addSpy
isn't filling null gaps but simply adds a spy to the end, isFull
could be rewritten to return spies.length == i;
.
这篇关于如何检查数组是否已满,如果未满则添加到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!