如何检查数组是否已满,如果未满则添加到数组中? [英] How check if array is full and if not full add to it?

查看:114
本文介绍了如何检查数组是否已满,如果未满则添加到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有阵列。我有一个 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();

        }
    }


推荐答案


  1. spies.length< 10 是不正确的。它应该是 spies.length> 0&&我< spies.length 以确保以下赋值 spies [i] = spy; 始终有效。

  1. spies.length < 10 isn't correct. It should be spies.length > 0 && i < spies.length to make sure that the following assignment spies[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;.

这篇关于如何检查数组是否已满,如果未满则添加到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆