java - CompareTo 方法不起作用?

标签 java class compareto

我收到这些错误

Java A5-1\SavingsAccountPart1Test.java:74: error: incompatible types: SavingsAccount cannot be converted to double
        if ( savings1.compareTo(savings2) > 0 )

Java A5-1\SavingsAccountPart1Test.java:76: error: incompatible types: SavingsAccount cannot be converted to double
        else if (savings1.compareTo(savings2) == 0 )

这是类(class)

import java.text.DecimalFormat;

public class SavingsAccount

{

    private double annualInterestRate; //A double for the yearly interest rate
    private double balance;            //A double for balance

    /**
        SavingsAccount A constructor for the annual interest rate and balance
    */
    public SavingsAccount()
    {
        //The balance and interest rate are given default values
        annualInterestRate = .005;
        balance = 0.00;
    }

    /**
        SavingsAccount A constructor for the annual interest rate and balance
        @param rate The annual interest rate
        @param bal The balance
    */
    public SavingsAccount( double rate, double bal )
    {
        //Allowing the client to set the balance and interest rate while checking if the values are valid
        if (rate < 0)
        {
            System.out.println("WARNING: Starting balance must not be negative; setting it to $0.00.");
            rate = .005;
        }
        else
            annualInterestRate = rate;

        if (balance < 0)
        {
            System.out.println("WARNING: Interest rate must not be negative; setting it to 0.5%.");
            bal = 0;
        }
        else
            balance = bal;
    }

    /**
        getInterestRate A method that returns the interest rate
        @return The annual interest rate
    */
    public double getInterestRate()
    {
        return annualInterestRate;
    }

    /**
        getBalance A menthod that returns the balance
        @return The balance
    */
    public double getBalance()
    {
        return balance;
    }

    /**
        update A method that updates the balance
        @param bal The Balance
    */
    public void update( double bal )
    {
        //make a money format, update balance by setting balance to passed in bal and
        //check if balance is overdrawn or not
        DecimalFormat money = new DecimalFormat("$#,##0.00");
        balance += bal;
        if (balance < 0)
            System.out.println("WARNING: ACCOUNT OVERDRAWN \n  Current balance: " + money.format(balance));
    }

    /**
        addInterest A method that will add interest to balance
    */
    public void addInterest()
    {
        //declare a monthly interest and a sub balance, then add interest if balance is greater than 0
        double monthlyInterest;
        double subBalance;
        if (balance > 0)
        {
            monthlyInterest = annualInterestRate / 12;
            subBalance = balance * monthlyInterest;
            balance += subBalance;
        }
    }

    /**
        compareTo A method to see if balance is bigger or smaller than savings
        @param savings The savings
        @return The result
    */
    public int compareTo( double savings )
    {
        int result;
        if (balance > savings)
            result = 1;
        else if (balance == savings)
            result = 0;
        else
            result = -1;

        return result;
    }

    /**
        toString A method that returns the balance and rate as a string
        @return The string of balance and rate
    */
    public String toString()
    {
        //makes format for money and interest rate
        //makes a string to hold the balance and rate then returns the string
        DecimalFormat money = new DecimalFormat("$#,##0.00");
        DecimalFormat rate = new DecimalFormat("0.0%");
        String balRate = ("Balance: " + money.format(balance) + "\n" +
                          "Annual Interest Rate: " + rate.format(annualInterestRate * 100));
        return balRate;
    }
}

以及测试类的代码(不允许更改)

import java.io.*;

import java.util.Scanner;

import java.text.DecimalFormat;

public class SavingsAccountPart1Test

{

    public static void main(String args[]) throws IOException
    {
        double interestRate;        // Annual interest rate
        double balance;             // Balance in the account
        double interestEarned;      // Interest earned
        double amount;              // Amount of a deposit or withdrawal
        double totalUpdates;        // Total amount deposited and withdrawn

        // Create a DecimalFormat object for formatting output.
        DecimalFormat df = new DecimalFormat("$#,##0.00");

        // Display your name
        System.out.println("[client] YOUR NAME");

        // Welcome message
        System.out.println("\n[client] Welcome to the Fleesum Bank"
            + "\n[client] This is the monthly interest calculator");

        // Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(System.in);

        // Create a SavingsAccount object using the no-argument constructor
        SavingsAccount savings1 = new SavingsAccount();

        // Display the initial state of savings1
        System.out.println("\n[client] First SavingsAccount object");
        System.out.println("\n[client] Balance: " + savings1.getBalance());
        System.out.println("[client] Interest Rate: " + savings1.getInterestRate());
        System.out.println("\n[client] Using toString:\n" + savings1.toString());

        // Create a SavingsAccount object using the 2-argument constructor
        SavingsAccount savings2 =
            new SavingsAccount(1000, 0.10);

        // Display the initial state of savings2
        System.out.println("\n[client] Second SavingsAccount object");
        System.out.println("\n[client] Balance: " + savings2.getBalance());
        System.out.println("[client] Interest Rate: " + savings2.getInterestRate());
        System.out.println("\n[client] Using toString:\n" + savings2.toString());

        // Test method addInterest when balance is >= 0
        savings2.addInterest();
        System.out.println("\n[client] Interest computed. New balance: "
            + savings2.getBalance());

        // update the balance:
        savings2.update( 50 );
        System.out.println("\n[client] Fifty dollars deposited. New balance: "
            + savings2.getBalance());
        // update, overdrawing the account
        savings2.update( -2000 );
        System.out.println("\n[client] Two thousand dollars withdrawn. New balance: "
            + savings2.getBalance());

        // Test method addInterest when balance is < 0
        savings2.addInterest();
        System.out.println("\n[client] Interest computed. New balance: "
            + savings2.getBalance());

        // Show final state of savings2:
        System.out.println("\n[client] Using toString:\n" + savings2.toString()
            + "\n");

        // Test compareTo method
        if ( savings1.compareTo(savings2) > 0 )
            System.out.println("[client] Savings1 has the larger balance");
        else if (savings1.compareTo(savings2) == 0 )
            System.out.println("[client] Savings1 and Savings2 "
            + "have the same balance");
        else
            System.out.println("[client] Savings2 has the larger balance");

        System.out.println();
    }
}

最佳答案

public int compareTo( double savings )

是您的问题,请将 double 替换为 SavingsAccount 并相应地修改方法。

关于java - CompareTo 方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29300236/

相关文章:

java - getSalary() 方法不起作用

class - 单击时如何更改特定(此)按钮类。使用 Vue.js 2.0

java - 比较方法违反了它的一般契约——但我可能想这样做?

Java CompareTo 对于不工作的对象

java - 在 HTML 中调用 Java 方法

java - Android中SOAP的HTTP GET方法,请纠正我

java - FileInputStream 抛出 NullPointerException

java - 如果我将整数字段添加到外部集合,我是否会发布此内容?

Python Tkinter : How do I avoid global variables in a changing class?

java - 从扩展类中覆盖 compareTo - 发生了什么?