gpt4 book ai didi

java - 我将如何循环回到开头?

转载 作者:行者123 更新时间:2023-11-30 11:25:44 24 4
gpt4 key购买 nike

如果数字为负数,我会尝试将其设置为让您重新开始并输入另一个数字的位置。我尝试做一个 while 循环,但它只是放入 System.out.println,我进入了一个无限循环。

    System.out.println("Please input a positive number: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();


if (num < 0) {
System.out.println("That number is negative.");
}

if (num >= 90 && num <= 110) {
boolean value = true;
} else if (num >= 190 && num <= 210) {
boolean value = true;
}

我以前做过一次这样的事情,我记得一旦我弄明白了它就很简单哈哈。不幸的是,我没有那个文件可以看。有帮助吗?

*编辑开始

   int num = scan.nextInt();
while (num < 0)
{
System.out.println("Please input a positive number: ");
Scanner scan = new Scanner(System.in);
}

*编辑 #2

Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
while (num < 0)
{
System.out.println("Please input a positive number: ");
}

*最终工作代码

   int num;
Scanner scan = new Scanner(System.in);

while (true)
{
System.out.println("Please input a positive number: ");
num = scan.nextInt();

if (num < 0)
{
System.out.println("That number is negative.");
}
else if ((num >= 90 && num <= 110) || (num >= 190 && num <= 210))
{
System.out.println("true");
break;
}
else
{
System.out.println("false");
break;
}

}

最佳答案

如果数字为负数,将再次提示用户,否则跳出循环。

   int num;
Scanner scan = new Scanner(System.in);

while (true)
{
System.out.println("Please input a positive number: ");
num = scan.nextInt();

if (num < 0)
{
System.out.println("That number is negative.");
}
else if ((num >= 90 && num <= 110) || (num >= 190 && num <= 210))
{
break;
}
}

关于java - 我将如何循环回到开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180563/

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