簡體   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