簡體   English   中英

println方法中的true / false布爾值

[英]true/false Boolean value inside println method

public void run(){
    int x = 9; 
    int y = 9;

    println( "true or false = " + (x == y) );
    println("true or false = " + ( x < y) );
    prinltn("true or false = " + (x > y) );

}

在一個示例中,我的書在println方法中使用括號()來測試某些東西是真還是假。 這是我第一次看到()在println方法中用作布爾測試。 以前我想用類似的方法解決問題

  if (x == y) {
     println("true or false = true");
  } else {
     println("true or false = false");
  }
  1. 我在哪里可以在println方法中找到有關布爾值的更多信息?
  2. 一個比另一個正確嗎? 我應該避免使用上述示例之一嗎?

一個比另一個正確嗎?

正確並不是真正描述它的正確術語,因為兩者都很好。 唯一的區別是代碼行。 所以不行。 他們倆都是對的。

我應該避免使用上述示例之一嗎?

不完全正確,但是我建議您像第一個一樣,開始使代碼盡可能短以使其易於維護。


至於那些println發生的事情,這只是一個簡單的String連接:

println("true or false = " + (x == y) );
//       true or false =       true

不,不要回避。 使用() 它不是在println內部。 這都是關於字符串串聯的。

為了進行更改,請嘗試執行以下語句並檢查結果。

println( "true or false = " + (x == y) );

println( "true or false = " +x == y) );

在以下情況下,將出現運算符優先級。

再說一遍,為什么在打印方法(x == y)使用括號,括號具有很高的精確度,所以其中的語句在對整個表達式求值之前先執行。

當您測試某件事是否為真時,該條件將成為布爾值( truefalse )。 布爾值可以像其他類型(如int )一樣分配和打印。 因此,如果您輸入:

System.out.println("true or false = " + (x == y));

它與執行操作相同:

boolean f = (x==y);
System.out.println("true or false = " + f);

與執行操作相同:

boolean f;
if (x==y) {
    f = true;
} else {
    f = false;
}
System.out.println("true or false = " + f);

這里()不用於布爾測試,它用於優先級。 如果您不使用(),則第一個x將被轉換為String,那么您不能將==與string和integer一起使用

(incompatible operand types String and int)

為了避免這種情況,我們必須使用()

(x == y) 

我可以建議您第一個示例是好的,它減少了行數。

println("true or false = " + (x == y) );

建議第一個是因為它的代碼行數相對較少,但這並不意味着另一個是不正確的。 如果有的話, 您想利用在x和y上完成的測試的布爾o / p來進一步在您的代碼中使用,那么您將必須->

boolean b=(x==y);

然后可以重新使用 “ b”。

嘗試這個 :

String result = (x == y) ? "true" : "false";
System.out.println("true or false = " + result);

暫無
暫無

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

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