我正试图把它带到哪里如果数字为负数,你重新开始并输入另一个数字。我尝试了一个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;
}
}
答案 0 :(得分:1)
如果数字为负数,这将再次提示用户,如果不是,则会跳出循环。
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;
}
}
答案 1 :(得分:0)
boolean value;
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
while(num < 0) {
System.out.println("Please enter a positive number: ");
num = scan.nextInt();
}
if (num >= 90 && num <= 110) {
value = true;
} else if (num >= 190 && num <= 210) {
value = true;
}
// rest of your code
将其置于while
循环中,只要数字为负数就会运行。