簡體   English   中英

是否可以通過這種方式使用布爾表達式?

[英]Is it possible to use a boolean expression in this manner?

我目前正在學習Java腳本並嘗試新事物,例如,我希望查看是否可以將布爾表達式設置為結束(如果該表達式檢測到從開始到結束的數字)。

或者換句話說,我想要的是3到8。我將明確說明我正在使用netbeans IDE。

在我的最后一個if語句中,我希望它結束​​詢問過程。 我希望它是一個簡單的修復程序,但是除非我創建了更多其他if語句,否則我想不出任何可以完成此操作的方法。

掃描儀輸入=新的Scanner(System.in);

int[][] table;

boolean stopasking = true;



    while (stopasking = true){

    System.out.println("Let's make a magic Square! How big should it be? ");
    int size = input.nextInt();


    if (size < 0)
    {
        System.out.println("That would violate the laws of mathematics!");
        System.out.println("");
    }
    else if (size >= 9)
    {
        System.out.println("That's huge! Please enter a number less than 9.");
        System.out.println("");
    }
    else if (size <= 2)
    {
        System.out.println("That would violate the laws of mathematics!");
        System.out.println("");
    }
    else if (size == 3)
    {
        stopasking = false;
    }


    }

您使用了assignmnent運算符=應該使用==代替

size<0時條件size<=2成立,因此if兩個都可以使用一個

while(stopasking){
    if (size <= 2) {
        System.out.println("That would violate the laws of mathematics!\n");
    } else if (size >= 9){
       System.out.println("That's huge! Please enter a number less than 9.\n");
    } else if (size == 3){
        stopasking = false;
    }
 }

您可以通過這種方式使用布爾表達式作為退出循環的條件。 有人會說這是一個比break更優雅的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM