gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:26:29 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com