有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java确保我正确地解决了这个问题

这是我的第一门编程课程,我想确保我正确地解决了这个问题。如果你能检查一下我的工作,我将不胜感激

在给定起始余额和支票对象数组的情况下,编写一个方法来计算并返回支票帐户的余额。您可以假设Check类已经存在,并且有一个方法可以从名为double getAmount()的特定Check对象获取金额

阵列未满,并且可能存在间隙–请确保在尝试访问之前测试是否存在对象!使您的代码适用于任意长度的数组

将为您提供该方法的标题:

public double computeBalance(double startingBalance, Check[] register) {

    int i = 0; // i must be initialized and declared somewhere at least
    double total = 0.0;

    while ((i >= check.length) && check[i] != null) { // is >= correct? you do i++!
           total = (total + getAmount(check[i])); // should you add/compute somewhere 
                                                      // the given amounts
           i++;

    }  

    System.out.println(total);
}

共 (4) 个答案

  1. # 1 楼答案

    我知道你要求的不仅仅是解决方案本身,但显然有更好的人来指导你。你可以用我的例子来参考其他人向你解释的内容

    public double computeBalance(double startingBalance, Check[] register) {
    
        // let's start off from the starting balance
        double total = startingBalance;
    
        // go over all elements starting from 0
        for (int i = 0; i < check.length; i++) {
    
            // make sure you did not encounter null element
            if (register[i] != null) {
    
                // increase the total by the amount of the Check
                total += register[i].getAmount();
            }
        }
    
        // and finally return the resulting value
        return total;
    }
    
  2. # 2 楼答案

    先别管编程了。如果我告诉你“这是你账户的起始余额”然后递给你一堆支票,让你计算期末余额,你会怎么做?一旦你明白了这一点,你就可以开始解决编程问题了

    一些问题:

    • 你在哪里追踪账户余额
    • 如果register中的一个插槽为空(即null),循环中会发生什么
    • 循环中的check变量是什么?在哪里申报?它真的应该被称为check
    • 函数被声明为返回double。你回来干什么
    • 你试过编译代码吗?会发生什么
  3. # 3 楼答案

    如果你能通过一个编译器运行你的代码(听起来你不能,或者至少没有人鼓励你这么做),它会告诉你它不知道icheckgetAmount是什么

    不引用方法参数的方法体通常会遗漏一些内容——尤其是如果参数声明是由讲师给出的

    再看看你的循环状况。开始时i的值是多少

  4. # 4 楼答案

    当你到达一个缺口时,执行就会结束。在循环中使用if语句进行空检查