gpt4 book ai didi

java - 循环用户输入直到满足条件

转载 作者:搜寻专家 更新时间:2023-11-01 01:35:37 25 4
gpt4 key购买 nike

我需要要求用户输入一个数字作为范围的开始,然后输入另一个数字作为范围的结束。起始数必须为 0 或更大,结束数不能大于 1000。两个数字都必须能被 10 整除。我找到了满足这些条件的方法,但是如果不满足,我的程序会告诉用户他们的输入不正确。我是否可以对其进行编码,以便在用户输入后检查以确保满足条件,如果它们没有循环并再次输入。这是我到目前为止的代码。

    Scanner keyboard = new Scanner(System.in);
int startr;
int endr;
System.out.println("Enter the Starting Number of the Range: ");
startr=keyboard.nextInt();
if(startr%10==0&&startr>=0){
System.out.println("Enter the Ending Number of the Range: ");
endr=keyboard.nextInt();
if(endr%10==0&&endr<=1000){

}else{
System.out.println("Numbers is not divisible by 10");
}
}else{
System.out.println("Numbers is not divisible by 10");
}

最佳答案

简单的do-while:

Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
System.out.println("Enter the Starting Number of the Range: ");
startr = keyboard.nextInt();
if(startr % 10 == 0 && startr >= 0)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);

good = false;
do
{
System.out.println("Enter the Ending Number of the Range: ");
endr = keyboard.nextInt();
if(endr % 10 == 0 && endr <= 1000)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);

// do stuff

关于java - 循环用户输入直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15843169/

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