while循环验证在java中

时间:2015-12-04 11:06:47

标签: java

我想在我的"会员"中创建一个while循环。构造函数(要遵循的代码 - 非常简单)以确保成员标识为10个字符,或者引脚编号为4个字符

e.g。虽然id​​ / pinNumber id不是10/4长 停止正在构建的构造函数 打印"请输入id / pinNumber长度为10/4个字符"

这是我的代码

 /**
 * Constructor for objects of class Member
 */
public Member(String giveName, String giveID, String givePinNumber, int giveMoney)
{
    memberName = giveName;
    id = giveID;
    if(id.length() > 10)
        System.out.println("Please input an id less than 10 characters");

    pinNumber = givePinNumber;
    if(pinNumber.length() > 10)
        System.out.println("Please input a pinNumber less than 10 characters");

    store = null;
    item = null;
    money = giveMoney;
}

2 个答案:

答案 0 :(得分:2)

由于这个问题似乎吸引了非常广泛/错误的答案,我将尝试澄清一些事情:

可能在构造函数中循环以从控制台获取输入,但我强烈建议不要使用那种代码:

Member(String giveName, String giveID, String givePinNumber, int giveMoney) {
    Scanner sc = new Scanner(System.in);

    id = giveID;
    while (id.length() != 10) {
        System.out.println("Enter id with length of 10: ");
        id = sc.nextLine();
    }

    pinNumber = givePinNumber;
    while (pinNumber.length() != 4) {
        System.out.println("Enter pin-number with length of 4: ");
        pinNumber = sc.nextLine();
    }

    store = null;
    item = null;
    money = giveMoney;

    sc.close();
}

通常这可以从创建成员对象的人那里完成!如果创建了成员对象,我可以使用main方法执行以下操作:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String id;
    System.out.println("Please enter id: (length must be 10)");
    while ((id = sc.nextLine()).length() != 10)
        System.out.println("Length of id must be 10, try again: ");

    String pin;
    System.out.println("Please enter id: (length must be 10)");
    while ((pin = sc.nextLine()).length() != 4)
        System.out.println("Length of pin must be 4, try again: ");

    sc.close();

    Member foo = new Member("Peter", id, pin, 1000000);
}

并且您的Member-constructor可能如下所示:

Member(String giveName, String giveID, String givePinNumber, int giveMoney) {
    if (giveID.length() != 10)
        throw new IndexOutOfBoundsException("ID-length must be 10!");
    if (givePinNumber.length() != 4)
        throw new IndexOutOfBoundsException("PIN-length must be 4!");

    id = giveID;
    pinNumber = givePinNumber;
    store = null;
    item = null;
    money = giveMoney;

}

此方法将使您的代码清晰可读但更重要:可重用!考虑一个java-app,你没有控制台...你将无法再使用你的会员课程了!

答案 1 :(得分:1)

我认为这种验证属于视图层:    *询问价值观    *进行验证    *显示错误并询问正确的值 当你调用构造函数时,传递给它的数据必须正常。

因此,您不需要在构造函数中进行验证。

实际上,构造函数的目标是初始化类的字段。没有验证,也没有抛出异常。