【问题标题】:how to create a subprogram that finds the sum of the elements entered by a user [closed]如何创建一个子程序来查找用户输入的元素的总和[关闭]
【发布时间】:2021-01-17 05:49:59
【问题描述】:

这是我写的子程序:

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[]));

【问题讨论】:

  • @Abra 我编辑了它并显示了我上面写的代码。
  • 如果你将一个有效的整数数组传递给方法,你的代码就可以工作。

标签: java arrays element subroutine


【解决方案1】:

你还没有声明整数数组

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));
    }

}

【讨论】:

  • 数组基于用户输入的利润(每辆车)。
  • 谢谢。如果我想计算用户在数组中所做的条目并将它们相加怎么办?
  • 是的。更新了答案。你能检查一下吗
  • 它有效。谢谢
【解决方案2】:

如果你想从控制台读取值,然后你想找到利润/总和,你可以使用 Scanner 类读取值并将这些值存储在数组中。

    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));

}

【讨论】:

    猜你喜欢
    • 2020-09-23
    • 1970-01-01
    • 2020-01-21
    • 2021-12-13
    • 1970-01-01
    • 2015-03-26
    • 2012-10-13
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多