在 Java 中的加法和連線


Java 中的“+”運算子既可用於新增數字,也可用於連線字串。應該考慮以下規則。

  • 只有數字為運算元,結果將是數字。

  • 只有字串為運算元,結果將是連線的字串。

  • 如果數字和字串都是運算元,則在字串之前出現的數字將被視為數字。

  • 如果數字和字串都是運算元,則在字串之後出現的數字將被視為字串。

  • 可以用括號來覆蓋上述規則。

示例

建立一個名為 Tester 的 Java 類。

Tester.java

即時演示

public class Tester {
   public static void main(String args[]) {      
      //Scenario 1: Only numbers as operands to + operator
      System.out.print("Scenario 1: (1 + 2)  = ");      
      System.out.println(1 + 2);

      //Scenario 2: Only Strings as operands to + operator
      System.out.print("Scenario 2: (\"tutorials\" + \"point.com\") = ");      
      System.out.println("tutorials" + "points.com");

      //Scenario 3: both numbers and strings as operands to + operator
      //numbers will be treated as non-text till a string comes
      System.out.print("Scenario 3: (1 + 2 + \"tutorials\" + \"point.com\") = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com");

      //Scenario 4: both numbers and strings as operands to + operator
      //if string comes first, numbers will be treated as text.
      System.out.print("Scenario 4: (1 + 2 + \"tutorials\" + \"point.com\" + 3 + 4 ) = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com" + 3 + 4);

      //Scenario 5: both numbers and strings as operands to + operator
      //if string comes first, numbers will be treated as text.
      //Use brackets to treat all numbers as non-text
      System.out.print("Scenario 5: (1 + 2 + \"tutorials\" + \"point.com\" + (3 + 4)) = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com" + (3 + 4));
   }
}

輸出

編譯並執行檔案以驗證結果。

Scenario 1: (1 + 2)  = 3
Scenario 2: ("tutorials" + "point.com") = tutorialspoints.com
Scenario 3: (1 + 2 + "tutorials" + "point.com") = 3tutorialspoints.com
Scenario 4: (1 + 2 + "tutorials" + "point.com" + 3 + 4 ) = 3tutorialspoints.com34
Scenario 5: (1 + 2 + "tutorials" + "point.com" + (3 + 4)) = 3tutorialspoints.com7

更新於:2020 年 6 月 18 日

1 千+ 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.