-2

我有一个名为 Human 的类(在构造函数中接受名称(字符串)和高度(int)),并且还需要创建这个类的供应商,它将创建一个对象,但我希望对象的名称在 5-10 个字符之间, 高度应在 110-250 之间。在Java中可以这样做吗?

4

2 回答 2

0

这是一种方法,拒绝无效的论点

public class Human {

    private final String name;
    private final int height;

    public Human(String name, int height) {
        validateName(name);
        validateHeight(height);
        this.height = height;
        this.name = name;
    }

    private void validateName(String name) {
        if(name==null || name.length()<5 || name.length()>10)
            throw new IllegalArgumentException("Name should be between 5-10 chars long but  "+name);
    }

    private void validateHeight(int height) {
        if(height<110 || height>250) 
            throw new IllegalArgumentException("Height should be between 110-250 but "+height);
    }
}

请注意,这是一个RuntimeException变体,包括引发检查异常并让客户端代码有一个解决方法。或者,也许有一个静态工厂方法,如果无效则返回一个 InvalidHuman 对象。

更新

好的,我想你想要这样的东西

public class HumanProvider {

    private static final Random r = new Random();

    private static String vowels = "aeiou";
    private static String cons = "bcdfghjklmnpqrstvwxyz";

    private static String[] patterns = "cvc vc cv cvvc vcc".split(" ");

    private HumanProvider() {
    } // don't instantiate

    public static Human createRandom() {

        String name;
        do {
            name = getRandomString();
        } while (name.length() < 5 || name.length() > 10);

        int height = r.nextInt(251 - 110) + 110;

        return new Human(name, height);
    }


    private static String getRandomString() {
        int numSyllabels = r.nextInt(5) + 1;
        StringBuilder name = new StringBuilder();
        for (int i = 0; i < numSyllabels; i++) {
            String pattern = patterns[r.nextInt(patterns.length)];
            for (char c : pattern.toCharArray()) {
                name.append(randomChar((c == 'c') ? cons : vowels));
            }
        }
        return name.toString();
    }

    private static char randomChar(String list) {
        return list.charAt(r.nextInt(list.length()));
    }
}
于 2017-11-15T20:52:35.387 回答
-1

构造函数不能直接返回 null,但您可以使用称为工厂方法的东西。工厂方法看起来像这样:

public static Human createHuman(String name, int height)
{
    if (height < 110 || height > 250) 
        return null;
    if (name == null || name.length() < 5 || name.length() > 10)
        return null;
    else
        return new Human(name, height);
}

private Human (String name, int height)  // note that this is private
{
    this.name = name;
    this.height = height;
}

你可以这样称呼它:

Human.createHuman("Steve", 117);

(或者在你的情况下,也许像这样:)

Supplier<Human> i = ()-> {return Human.createHuman(someName, someHeight)};
于 2017-11-15T21:04:18.660 回答