如果我想检查用户给定的整数是否为正数,并且如果它没有向控制台返回要求重新输入数字的消息,我该如何实现它?我正在按照下面的代码思考一些事情,但无法继续我的思路。不知道在 else 语句中键入什么。任何帮助,不胜感激。
int nJudges = readInt("Enter number: ");
while(nJudges <= 0){
nJudges = readInt("Enter number: ");
}
好吧,你是对的。谢谢。这就解决了。
怎么样
int num = readInt("Enter number: ");
while(num <= 0)
num = readInt("Please enter a number greater than zero: ");
或
int num;
do {
num = readInt("Please enter a number greater than zero: ");
} while (num <= 0);
这个想法应该有点像这样
int num = readInt("Enter number: ");
while(num <= 0){
num = readInt("Enter number: ");
}
一个例子:
// a place to store user's selection
int selection = -1;
// this bit creates a while loop that assigns the input to `selection` using
// your `readInt` function. It's condition is that the result is greater than 0
while ((selection = readInt("Enter a number:")) < 0){
// prompt user to select a valid number
System.out.println("Please enter a valid number!");
}
// `selection` now stores the user's selection
enter code here
现在,您有用户选择selection
了解 while 循环(使用链分配):
在 Java 中,赋值是右关联。这意味着像 a=(b=c)
这样的表达式应该为a
和b
分配c
。为此,赋值运算符=
返回正确操作数的值。因此,表达式a=b
返回 b
,以及我们在 while 循环中使用的表达式:
(selection = readInt("Enter a number:"))
返回用户的输入。
int num = 0;
do
{
num = readInt("Enter number: ");
if (num <= 0)
System.out.println("number is not positive");
}while (num <= 0);