如何创建一个子程序来查找用户输入的元素的总和

how to create a subprogram that finds the sum of the elements entered by a user

这是我写的子程序:

public static int profitCalc(int num[])
{
    int sum = 0;
    
    for (int i = 0; i < num.length; i = i + 1)
    {
        sum +=  num[i];
    }
    return sum;
}

但是当我输入它时(如下面的代码),它给我一个错误。

System.out.println(profitCalc(profit[]));

您还没有声明整数数组

int[] profit = new int[]{1,2,3,4,5}; 
System.out.println(profitCalc(profit));

完整代码:

    class Main {
    public static int profitCalc(int num[])
    {
        int sum = 0;

        for (int i = 0; i < num.length; i = i + 1)
        {
            sum +=  num[i];
        }
        return sum;
    }

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("Enter no of vechile:");
        int noOfVechile = input.nextInt();
        int[] profit = new int[noOfVechile];
        for(int i=0;i<profit.length;i++){
            System.out.println("Enter profit of vechile "+(i+1));
            int profitPerVechile = input.nextInt();
            profit[i]=profitPerVechile;
        }

        System.out.println(profitCalc(profit));
    }

}

如果您想从控制台读取值,然后想找到 profit/sum,您可以使用扫描器 class 读取值并将这些值存储在数组中。

    public static int profitCalc(int num[]) {
    int sum = 0;

    for (int i = 0; i < num.length; i = i + 1) {
        sum += num[i];
    }
    return sum;
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int profitsLenth = scanner.nextInt();
    int[] profits = new int[profitsLenth];
    for (int i = 0; i < profits.length; i++) {
        profits[i] = scanner.nextInt();
    }

    System.out.println(profitCalc(profits));

}