2016-11-30 54 views
0

我試圖返回數組中所有值的總和,同時也嘗試將最大值返回給主方法,但是,程序指出我在返回總數和返回數時有錯誤。錯誤狀態「類型不匹配:不能從int轉換爲int []」。如何返回數組來計算總數並找到最大值?

public static void main(String[] args) { 
    Scanner number = new Scanner(System.in); 
    int myArray[] = new int[10]; 
    for(int i = 0; i <= myArray.length-1; i++) { 
     System.out.println("Enter Number: "); 
     int nums = number.nextInt(); 
     myArray[i] = nums; 
    } 
    int [] sum = computeTotal(myArray); 
    System.out.println("The numbers total up to: "+sum); 
    int [] largest = getLargest(myArray); 
    System.out.println("The largest number is: "+largest); 
} 

public static int[] computeTotal(int myArray[]) { 
    int total = 0; 
    for (int z : myArray){ 
     total += z; 
    } 
    return total; 
} 
public static int[] getLargest(int myArray[]) { 
    int number = myArray[0]; 
    for(int i = 0; i < myArray.length; i++) { 
     if(myArray[i] > number) { 
      number = myArray[i]; 
     } 
    } 
    return number; 
} 
+0

有時錯誤消息可能會令人困惑。不是在這種情況下。 'return number'試圖返回一個int,但是方法的返回類型是'int []' –

+0

哇......我的部分顯然是失敗的。無論如何,謝謝! –

回答

0

的方法computeTotalgetLargest應該改變的返回類型爲int。請參考:

public static void main(String[] args) { 
     Scanner number = new Scanner(System.in); 
     int myArray[] = new int[10]; 
     for(int i = 0; i <= myArray.length-1; i++) { 
      System.out.println("Enter Number: "); 
      int nums = number.nextInt(); 
      myArray[i] = nums; 
     } 
     int sum = computeTotal(myArray); 
     System.out.println("The numbers total up to: "+sum); 
     int largest = getLargest(myArray); 
     System.out.println("The largest number is: "+largest); 
    } 

    public static int computeTotal(int myArray[]) { 
     int total = 0; 
     for (int z : myArray){ 
      total += z; 
     } 
     return total; 
    } 
    public static int getLargest(int myArray[]) { 
     int number = myArray[0]; 
     for(int i = 0; i < myArray.length; i++) { 
      if(myArray[i] > number) { 
       number = myArray[i]; 
      } 
     } 
     return number; 
    } 

希望得到這個幫助。

0

可能在java8中有更簡單的方法來獲得最大值和總和。

int sum = Arrays.stream(new int[] {1,2, 3}).sum();   //6 
int max = Arrays.stream(new int[] {1,3, 2}).max().getAsInt(); //3 
相關問題