繁体   English   中英

Java中的有效性检查

[英]Validity check in java

如果我要检查用户整数给定的值是否为正,并且是否没有向控制台返回消息以要求重新输入该数字,我该如何实现? 我正在按照下面的代码思路进行思考,但无法继续我的思路。 不知道在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)这样的表达式应将c分配给ab 为此,赋值运算符=返回右操作数的值。 因此,表达式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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM