如何使循环在Java netbeans中更有效

时间:2018-12-23 15:20:32

标签: java oop netbeans

我是Java的新手,我正在用Java实现一个图书系统项目。我创建了一个循环,用于验证如果年龄小于18岁的客户年龄,如果大于18岁的客户可以继续上课,则需要父母提供。

当客户输入的年龄小于18岁(我希望该功能执行此操作)时,循环结束。但是,当年龄大于18岁时,年龄规定的警告会显示年龄大于18岁。

我已经包含了else语句,但是代码仍继续在终端中显示。 System.out.println(“您未满18岁,就不能没有父母的监督!”),即使年龄大于18岁。

请让我知道循环中需要调整的内容,这样更有效

//验证客户年龄/年龄限制

while (true) {

    System.out.println("Pleaste enter your age");
    customerAge = sc.nextInt();

    if (customerAge < 18) {

    }

    System.out.println("You can not proceed without parent supervision as you are under the age of 18 !");

    if (customerAge > 17) {
        break;

    }
    continue;
}

3 个答案:

答案 0 :(得分:0)

我不确定这是否是您的家庭作业,但这不是您应该检查的方式:

with in while
    if (customerAge < 18) {
         // print the warning message
         break from for loop
    } 
    //do your stuff this mean customer is an adult.

您的打印声明不受测试条件的保护,因此您也看到它已为成人客户打印。

答案 1 :(得分:0)

这是您在while循环中验证这一点所需的全部内容,

while (true) {
    System.out.println("Pleaste enter your age");
    customerAge = sc.nextInt();

    if (customerAge < 18) {
        System.out.println("You can not proceed without parent supervision as you are under the age of 18 !");
        break;
    }
}

答案 2 :(得分:0)

该消息应位于if块内:

while (true) {
    System.out.println("Pleaste enter your age");
    customerAge = sc.nextInt();
    if (customerAge < 18) {
        System.out.println("You can not proceed without parent supervision as you are under the age of 18 !");
        continue;
    }    
    break;
}

目前尚不清楚,如果年龄小于18岁,为什么要停止循环?
如果年龄> = 18,会发生什么?

相关问题