簡體   English   中英

Java代碼,將參數傳遞給方法

[英]Java code, passing arguments to method

我不確定在這里做錯了什么,這是我的代碼

package methods;

public class example {
    public static int sum(int x, int y){ 
        return x+y; 
    }
    public static void printSomething() {
        int a = 1; 
        int b = 2; 
        System.out.println("The sum of "+ x + " and "+ y +" is "+sum(a,b)); 
    }
    public static void main(String[] args) {
        System.out.println("Hello"); 
        printSomething();
    }
}

我想打印x和y的總和是3

嘗試這個:

System.out.println("The sum of "+ a + " and "+ b +" is "+sum(a,b)); 

參數名稱xy對於方法定義而言是局部的,在當前范圍內,它們分別稱為ab

另外,為了保持一致性,您可以在printSomething()方法printSomething() ab重命名為xy 結果將完全相同,但是現在變量將具有相同的名稱。

package methods;

public class example {
    public static int sum(int x, int y){ 
        return x+y; 
    }
    public static void printSomething() {
        int a = 1; 
        int b = 2; 
        System.out.println("The sum of " + a + " and " + b + " is " + sum(a,b)); 
    }
    public static void main(String[] args) {
        System.out.println("Hello"); 
        printSomething();
    }
}

您無法以這種方式在其他方法內部訪問局部變量(例如sum方法的x,y)。

我不確定要達到的目標,但是請檢查是否有幫助:

package methods;

public class example {
    public static int sum(int x, int y){ 
        return x+y; 
    }
    public static void printSomething() {
        int a = 1; 
        int b = 2; 
        System.out.println("The sum of "+ a + " and "+ b +" is "+sum(a,b)); 
    }
    public static void main(String[] args) {
        System.out.println("Hello"); 
        printSomething();
    }
}

暫無
暫無

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

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