Java 中的方法可以返回多個值嗎?


您可以在 Java 中僅返回一個值。如果需要,您可以使用陣列或物件返回多個值。

示例

在下面給出的示例中,calculate() 方法接受兩個整型變數,對它們執行加、減、乘、除運算,將結果儲存在陣列中並返回陣列。

public class ReturningMultipleValues {
   static int[] calculate(int a, int b){
      int[] result = new int[4];
      result[0] = a + b;
      result[1] = a - b;
      result[2] = a * b;
      result[3] = a / b;
      return result;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of a: ");
      int a = sc.nextInt();
      
      System.out.println("Enter the value of b: ");
      int b = sc.nextInt();
      int[] result = calculate(a, b);
      
      System.out.println("Result of addition: "+result[0]);
      System.out.println("Result of subtraction: "+result[1]);
      System.out.println("Result of multiplication: "+result[2]);
      System.out.println("Result of division: "+result[3]);
   }
}

輸出

Enter the value of a:
20
Enter the value of b:
10
Result of addition: 30
Result of subtraction: 10
Result of multiplication: 200
Result of division: 2

更新於: 2019 年 7 月 30 日

9K+ 瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.