2015-10-15 173 views
0

我在學習方法,我開始從三個整數中找出最大值。我嘗試運行它,它告訴我,我還沒有初始化result。我知道我沒有,但我不知道到底是什麼初始化它。我很可能會在代碼中搞砸或忘記了一些東西,所以如果你能指出我的意思,我將不勝感激!我該如何初始化?

import java.util.Scanner; 

public class MinMaxAvg { 

    public static void main(String[] args) { 
     int i = 5; 
     int j = 2; 
     int k = 3; 
     int l = max(i, j, k); 
     System.out.println ("The maximum of " + i + " and " + j + " and " + k + " is " + l); 
    } 

    public static int max (int num1, int num2, int num3) { 
     int result; 

     if (num1 > num2 || num1 > num3) { 
      result = num1; 
     } else if (num2 > num1 || num2 > num3) { 
      result = num2; 
     } else if (num3 > num1 || num3 > num2) { 
      result = num3; 
     } 
     return result; 
    } 
} 

回答

0

初始化

int result; 

int result = 0; 
0

當你聲明方法內的所有方法變量作爲一個局部變量,你必須在使用前初始化。 試試這個代碼:

import java.util.Scanner; 

public class MinMaxAvg { 

public static void main(String[] args) { 

int i = 5; 
int j = 2; 
int k = 3; 
int l = max(i, j, k); 
System.out.println ("The maximum of " + i + 
    " and " + j + " and " + k + " is " + l); 
    } 

public static int max (int num1, int num2, int num3) { 

int result=0;//initialize here by 0 or any other value 

if (num1 > num2 || num1 > num3) { 
    result = num1; 

} else if (num2 > num1 || num2 > num3) { 
    result = num2; 

} else if (num3 > num1 || num3 > num2) { 
    result = num3; 

} 

return result; 
} 
} 

,如果你仍然想使用int result沒有初始化它,那麼你必須聲明爲實例變量,如:

public class MinMaxAvg { 
    static int result; 
    } 

的更多信息,你可以訪問這個: https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

0

你會用某個默認值初始化局部變量int result = Integer.Integer.MIN_VALUE

1
public static int max (int num1, int num2, int num3) { 
    int max = num1; 

    if (num2 > max) { 
     max = num2; 
    } 

    if (num3 > max) { 
     max = num3; 
    } 

    return max ; 
} 

Java是很酷的,所以,如果你想獲得幻想,做到這一點

public static int max(int... args) 
{ 
    int max = Integer.MIN_VALUE; 

    for (int a : args) 
    { 
     if (a > max) 
     { 
      max = a; 
     } 
    } 

    return max; 
} 
相關問題