java中的有效性检查

时间:2014-01-03 20:19:34

标签: java

如果我想检查用户整数给定的是否为正数,并且如果它没有向控制台返回要求重新输入数字的消息,我该如何实现它?我正在考虑下面的代码,但不能继续我的思路。不知道在else语句中键入什么。任何帮助表示赞赏。

   int nJudges = readInt("Enter number: ");
        while(nJudges <= 0){
            nJudges = readInt("Enter number: ");
        }

好的,你是对的。非常感谢你。这已经解决了。

4 个答案:

答案 0 :(得分:3)

怎么样

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);

答案 1 :(得分:2)

这个想法应该有点像这样

int num = readInt("Enter number: ");
while(num <= 0){
    num = readInt("Enter number: ");
}

答案 2 :(得分:1)

一个例子:

// 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循环(using chain assignment

在Java中,assignment is right associative。这意味着像a=(b=c)这样的表达式应该为ca分配b。为此,赋值运算符=返回右操作数的值。因此,表达式a=b返回b,以及我们在while循环中使用的表达式:

(selection = readInt("Enter a number:"))

返回用户的输入。

答案 3 :(得分:0)

int num = 0;
do
{
    num = readInt("Enter number: ");
    if (num <= 0)
        System.out.println("number is not positive");
}while (num <= 0);