java - 在 Do while 循环验证中添加 Int 验证

标签 java loops validation do-while

import java.util.Scanner;
import java.util.*; 

public class ICT2100_LabTutorial2 {
    public static void main(String args[]){

        Scanner input = new Scanner(System.in);

        System.out.println("Enter your title: ");

        String title = input.nextLine();

        int page;
        int counter = 1;

        String value;

        do{
            System.out.println("Chapter " + counter++);
            value = input.nextLine();
            if(value.length() > 44)
            {
                System.out.println("More than 44 characters");
            }

            System.out.println("Enter a page number: ");
            page = input.nextInt();

            while((page < 1) && (page > 1500)){
                System.out.println("Enter a page number that is between 1 to 1500: ");
                page = input.nextInt();
            }

        }while(!value.equals("END"));

        System.out.println("you ended the process");
    }
}

我正在尝试将页码添加到我的代码中,而如果页码不是 1 到 1500 之间的数字,代码将告诉用户再次输入页码。

我能够正确运行代码,并且可以在没有页面计数器的情况下结束程序,但是一旦我添加了页面计数器段,​​程序就会中断或无法按预期运行。

编辑:显然你必须在 input.nextInt(); 之后添加 input.nextLine(); 程序才能真正继续并获取下一个指令而不是陷入循环。如果我错了请纠正我,仍在学习并感谢所有帮助。

最佳答案

使用

while((page < 1) || (page > 1500)) {
...
}

关于java - 在 Do while 循环验证中添加 Int 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52443186/

相关文章:

validation - 如何在 h :inputTextarea 上设置 maxlength 属性

Java 函数中的数组赋值

java - Selenium 网络驱动程序 : How many times does a driver try to find element with an implicit wait timeout?

java - Spring Data 中的重构返回 List<Object[]>

C++ 在到达输入末尾后结束 do while 循环

python - 运行时错误 : input() already active - file loop

javascript - 正则表达式在循环中的第一个匹配处停止

jquery - 如何验证提交按钮上的复选框?

java - 扩展 Spring Cloud Config Client 的正确方法是什么?

Java Bean Validation 2.0 Hibernate Validator - 具有外部 XML 配置的可执行 JAR