我開始學習考試並用方法做一些練習程序,目前我的思維已經空白。我想知道如何初始化n1,n2,n3和n4。我將它們設置爲0,但返回語句只返回0。如何解決變量可能未被初始化的錯誤
public class LargestOfIntegers2
{
public static int findLargest(int n1, int n2, int n3, int n4)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first integer --> ");
n1 = scan.nextInt();
System.out.print("Enter the second integer --> ");
n2 = scan.nextInt();
System.out.print("Enter the third integer --> ");
n3 = scan.nextInt();
System.out.print("Enter the fourth integer --> ");
n4 = scan.nextInt();
if(n1>n2 && n1 > n3 && n1 > n4)
return n1;
else if(n2 > n1 && n2 > n3 && n2 > n4)
return n2;
else if(n3>n1 && n3>n2 && n3>n4)
return n3;
else
return n4;
}
public static void main(String[] args) {
int n1, n2, n3, n4;
findLargest(n1, n2, n3, n4);
if(n1>n2 && n1 > n3 && n1 > n4)
System.out.println("Out of the numbers " + n1 + ", " + n2 + ", " + n3 + ", " + n4 + ", the largest integer is " + n1);
else if(n2 > n1 && n2 > n3 && n2 > n4)
System.out.println("Out of the numbers " + n1 + ", " + n2 + ", " + n3 + ", " + n4 + ", the largest integer is " + n2);
else if(n3>n1 && n3>n2 && n3>n4)
System.out.println("Out of the numbers " + n1 + ", " + n2 + ", " + n3 + ", " + n4 + ", the largest integer is " + n3);
else
System.out.println("Out of the numbers " + n1 + ", " + n2 + ", " + n3 + ", " + n4 + ", the largest integer is " + n4);
}
}
如果您不使用'n1,..,n4'原始值,爲什麼您將它們作爲參數傳遞?它們不應該是局部變量嗎? – MondKin 2014-12-11 01:45:58
'我將它們設置爲0' - 在哪裏?我沒有看到它...... – August 2014-12-11 01:46:50
你似乎期待從方法中獲得所有四個值。但是Java不能這樣工作 - 它是「按值傳遞」,而不是「通過引用傳遞」。如果您需要從方法中獲取所有四個值,則一種選擇是返回一個數組。您可能希望有一種方法僅從用戶獲取值,另一種方法是計算出最大值的方法。 – 2014-12-11 01:46:58