2015-12-06 40 views
0

我正在學習如何返回一個值並嘗試寫下面的代碼;返回一個值。輸出總是打印0

public class JustTryingReturn { 

static int a, b; 
static Scanner sc = new Scanner(System.in); 
static int nganu() { 
return a+b; 
} 

public static void main(String[] args) { 
    int c = nganu(); 
    System.out.println("Enter number "); 
    a = sc.nextInt(); 
    b = sc.nextInt(); 
    System.out.println(c); 
} 

} 

但是輸出總是打印0而不是a+b。我做錯了什麼? 謝謝。

回答

2

您應該撥打電話

int c = nganu(); 

分配的ab輸入值後。否則,當你計算它們的總和時,它們默認仍然包含0

System.out.println("Enter number "); 
a = sc.nextInt(); 
b = sc.nextInt(); 
int c = nganu(); 
System.out.println(c); 
+0

感謝。我覺得很愚蠢。 –

1

你要調用你的函數你賦值ab
所以把這個:int c = nganu();得到ab後。

0

請相應更改代碼,

public static void main(String[] args) { 
    //int c = nganu(); // here first time a,b is 0, still you haven't assign... 
    System.out.println("Enter number "); 
    a = sc.nextInt(); // now, actually you have assign value to a 
    b = sc.nextInt(); // now, actually you have assign value to b 
    int c = nganu(); 
    System.out.println(c); 
} 
2

嘗試使用這條線的順序這只是變化:

int c = nganu(); 
a = sc.nextInt(); 
b = sc.nextInt(); 

這樣的:

public class JustTryingReturn { 
    static int a, b; 

static Scanner sc = new Scanner(System.in); 
static int nganu() { 
return a+b; 
} 

public static void main(String[] args) { 

    // the order was changed 
    System.out.println("Enter number "); 
    a = sc.nextInt(); 
    b = sc.nextInt(); 
    int c = nganu(); 
System.out.println(c); 
} 

    }