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



我是java的新手,我正在用java实现一个书籍系统项目。我创建了一个循环,如果客户<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;
}

消息应该在 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,会发生什么?

我不确定这是否是你的家庭作业,但你应该如何检查:

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

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

这就是您在 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;
    }
}

最新更新