2016-11-30 41 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 
相关问题