简体   繁体   English

Java中具有子类的getter方法上的类型不兼容

[英]Incompatible types on getter method in java with subclasses

I have read through a number of different stack overflow questions that have a similar issue but not what I'm struggling with specifically. 我已经阅读了许多不同的堆栈溢出问题,这些问题都有类似的问题,但不是我正在专门解决的问题。 I have created a total of 4 classes, a Bill class, a Money class and a Date class as well as a driver to test my output. 我总共创建了4个类,一个Bill类,一个Money类和一个Date类,以及一个驱动程序来测试我的输出。 These classes are supposed to be implemented for use in managing a set of outstanding and paid bills. 这些类应实现为用于管理一组未付帐单和已付帐单。 When I attempt to run my main on my driver class I receive a "Incompatible types, money cannot be converted to int" and it points to my getDollars method. 当我尝试在驱动程序类上运行main时,我收到一个“不兼容的类型,金钱无法转换为int”,它指向我的getDollars方法。 I am fairly new to java so my solution may be simple but I don't see what I'm doing wrong. 我对Java相当陌生,因此我的解决方案可能很简单,但我看不到我做错了什么。 Should I be returning an object? 我应该归还物品吗?

    public class Money {
    //private instance variables used for tracking dollars and cents
    //private to avoid privacy leaks
    private int dollars;
    private int cents; 

    //constructor initializing dollars
    public Money(int dol){
        setDollars(dol);
    }

    //constructor initializing dollars and cents
    public Money(int dol, int cent){
        setDollars(dol);
        setCents(cent);
    }

    //constructor 
    public Money(Money other){
        setDollars(other.dollars);
        setCents(other.cents);

    }

    //setter for dollars
    public void setDollars(int dol){
        invalidDollars(dol);
        dollars = dol;
    }

    //getter for dollars
    public int getDollars(){
        return new Money(dollars);
    }

    //setter for cents
    public void setCents(int cent){
        invalidCents(cent);
        cents = cent;
    }

    //getter for cents
    public int getCents(){
        return new Money(cents);
    }

    //getter for total monetary amount, returned as a double
    public double getMoney(){
        dollars = (double)dollars;
        cents = (double)cents;
        return dollars + cents;
    }

    //setter for dollars and cents
    public void setMoney(int dol, int cent){
        setDollars(dol);
        setCents(cent);
    }

    //method to add the passed in int to dollars
    public void add(int dol){
        dollars += dol;
    }

    //method that adds the two ints passed in to dollars and cents
    public void add(int dol, int cent){
        //checks if addition caused cents to go over 99 limit
        if(cents + cent > 99){
            cent = cent - 100;
            dol += dol + 1;
        }
        dollars += dol;
        cents += cent;
    }


    //method that adds to this object the dollars and cents stored in 
    //the other object
    public void add(Money other){
        add(other.dollars, other.cents);
    }

    //determines if this money object is equal to that money object
    @Override
    public boolean equals(Object o) {
        if( o == null || ! (o instanceof Money) ) {
            return false;           
        } else {
        Money that = (Money)o;      
        return this.dollars == that.dollars && this.cents == that.cents;
    }
    }

    //prints out a Money object in the form of "$0.00"
    public String toString(){
        return "$"+ dollars +"."+ String.format("%02d", cents);
    }

    //checks if value for dollar is greater than zero,
    //if not the system will print out an error message
    //and crash
    public void invalidDollars(int val){
        if( val < 0){           
            System.err.println("Invalid cent value: " + val);
            System.exit(-1);
    }
    }

    //checks if value for cents is greater than zero and less
    //than 99, if not the system will print out an error
    //message and crash
    public void invalidCents(int val){
        if( val < 0 || val > 99){           
            System.err.println("Invalid cent value: " + val);
            System.exit(-1);
    }
    }
}

This is the class that has an error when I run it in my driver. 当我在驱动程序中运行该类时,该类有错误。 The other classes are 其他类是

public class Bill {
    //private data member initialization
    private Money amount;
    private Date dueDate;
    private Date paidDate = null;
    private String originator;

    //constructor
    public Bill(Money amount, Date dueDate, String originator){
        this.amount = new Money(amount);
        this.dueDate = new Date(dueDate);
        this.originator = new String(originator);   
    } 

    //copy constructor
    public Bill(Bill toCopy){ 
        this.amount = new Money(toCopy.amount);
        this.dueDate = new Date(toCopy.dueDate);
        this.originator = new String(toCopy.originator);
    }

    //method to get dueDate
    public Date getDueDate(){
        return new Date(dueDate);
    }

    //method to get originator
    public String getOriginator(){
        return new Bill(originator);
    }

    //checking if the bill has been paid
    public boolean isPaid(Date tempPaidDate){
        if(tempPaidDate == null){
            return false;
        } else {
            return true;
        }
    } 

    //method to check if the date the bill was paid was before the dueDate,
    //if so, it sets the onDay to the paidDate
    public void setPaid(Date onDay){ 
        if(onDay.precedes(dueDate)){
        paidDate = new Date(onDay);
        } else {
            setUnpaid();
        }
    }

    //method to set paidDate to null, meaning unpaid
    public void setUnpaid(){
        paidDate = new Date(null);
    }

    //method to set due date. if there is a paidDate (it does not equal null)
    //then it checks if the new dueDate is before the paidDate using the precedes
    //method from the date class. If the paidDate precedes the dueDate, then the
    //dueDate can be changed to the argument nextDate
    public void setDueDate(Date nextDate){ 
        if(paidDate != null){
            if(paidDate.precedes(nextDate)){        
        dueDate = new Date(nextDate);
        }
        }
    }

    //setter method for money amount
    public void setAmount(Money tempAmount){
        amount = new Money(tempAmount);
    }

    //getter method from Money class for the bill amount
    public Money getAmount(){ 
        return new Bill(amount);
    }

    //method to set the originator
    public void setOriginator(String tempOriginator){
        originator = new String(tempOriginator);
    }

    //toString method to print out the bill information including the amount, the dueDate, who the money should go to,
    //if it is paid, and if so, the date it was paid. If it has not been paid, the paidDate will return null
    public String toString(){
        return "Amount: " + amount + " Due: " + dueDate + " To: " + originator + " Paid: " + isPaid(paidDate) + " Date: " + paidDate;
        // build a string that reports the amount, 
        //when its due, to whom, whether paid, and if paid, the date paid.
    }

    //determine if two bills are equal by checking and comparing the amount, dueDate and originator
    @Override
    public boolean equals(Object toCompare) {
        if( toCompare == null || ! (toCompare instanceof Bill) ) {
            return false;           
        } else {
        Bill that = (Bill)toCompare;        
        return this.amount.equals(that.amount) && this.dueDate.equals(that.dueDate) && this.originator.equals(that.originator);
    }
    }
}

Date Class 日期类别

   public class Date {
    //private instance variables used for tracking month, day and year.
    //private to avoid privacy leaks
    private int month;
    private int day;
    private int year;

    //constructor
    public Date(){
    }

    //constructor
    public Date(int month, int day, int year){
        setDate(month, day, year);
    }

    //copy constructor
    public Date(Date aDate){
        //crashes if date is null
        if( aDate == null){
            System.out.println("Bad Date.");
            System.exit(0);
        }
        setMonth(aDate.month);
        setDay(aDate.day);
        setYear(aDate.year);
    }

    //setter for date taking in for argument temporary ints for each variable
    public void setDate(int tempMonth, int tempDay, int tempYear){
        setMonth(tempMonth);
        setDay(tempDay);
        setYear(tempYear);
    }

    //getter method for day
    public int getDay() {
        return day;
    }

    //setter method for day, first checks if the day
    //is within the bounds of 1 and 31. If the day is
    //invalid, the system will crash after printing out
    //an error message using the method invalidDate
    public void setDay(int tempDay) {
        if(tempDay >= 1 && tempDay <= 31) {
            day = tempDay;
        } else {
            invalidDate(tempDay);
        }
    }

    //getter for month
    public int getMonth() {
        return month;
    }

    //setter for month. first checks if the temporary month
    //taken in as argument is within the bounds of 1 and 12.
    //if not the system will crash after printing out an error
    //message using the invalidDate method.
    public void setMonth(int tempMonth) {
        if( tempMonth >= 1 && tempMonth <= 12) {
            month = tempMonth;
        } else {
            invalidDate(tempMonth);
        }
    }

    //getter for year
    public int getYear() {
        return year;
    }

    //setter for year. first checks if the temporary year taken 
    //in as argument is within the bounds of 2014 and 2024. if not
    //the system will crash after printing out an error message 
    //using the invalidDate method.
    public void setYear(int tempYear) {
        if( tempYear >= 2014 && tempYear <= 2024) { //maybe change this?
            year = tempYear;
        } else {
            invalidDate(tempYear);
        }
    }

    //method to printout an error message of the bad
    //date component and crash the system.
    public void invalidDate(int val) {
        System.err.println("Bad date component: " + val);
        System.exit(-1);
    }

    //string method that returns the date in the format 
    // mm\\dd\\yyyy
    @Override
    public String toString() {
        return month + "\\" + day + "\\" + year;
    }

    //equals method checking if each component of the two dates
    //being compared are equal. returns true or false
    @Override
    public boolean equals(Object other) {
        if( other == null || ! (other instanceof Date) ) {
            return false;           
        } else {
        Date that = (Date)other;        
        return this.year == that.year && this.month == that.month && this.day == that.day;
    }
    }

    //method to check if one date is before another date.
    //returns true or false after checking each date component 
    public boolean precedes(Date otherDate){
        return ((year < otherDate.year)||
                (year == otherDate.year && month <
                otherDate.month) ||
                (year == otherDate.year && month == otherDate.month
                && day < otherDate.day));
    }
}

Driver 司机

    public class BillMoneyDateDriver
{

    /**
     main driver function
     pre:  none
     post: exercises the methods in Bill, Money, and Date (not done)
     */
    public static void main(String[] args)
    {
        //Construct some money
        Money money1 = new Money(10);
        Money money2 = new Money(money1);
        money1.setMoney(30,50);
        //TODO: do more functional exercises with the money class


        System.out.println("Money objects output:");
        System.out.println(money1);
        System.out.println(money2);


        //Construct some bills
        Money amount = new Money(20);
        Date dueDate = new Date(4, 30, 2007);
        Bill bill1 = new Bill(amount, dueDate, "The phone company");

        Bill bill2 = new Bill(bill1);
        bill2.setDueDate(new Date(5, 30, 2007));
        amount.setMoney(31, 99);
        dueDate.setDay(29);
        Bill bill3 = new Bill(amount, dueDate, "The record company");

        System.out.println("Bill objects output:");
        System.out.println(bill1);
        System.out.println(bill2);
        System.out.println(bill3);

    }
}

This code is trying to return an int, but you are providing a new Instance of Money 这段代码试图返回一个int,但是您提供了一个新的Money实例

public int getDollars(){
    return new Money(dollars);
}

maybe you want (???) 也许你想要(???)

public int getDollars(){
    return this.dollars;
}

If not, where is dollars coming from? 如果没有, dollars从何而来?

Scary Wombat corrected few methods.You also need to change the getMoney() if you want to get the money like xx.xx. 可怕的Wombat纠正了几种方法。如果您想获得类似xx.xx的钱,还需要更改getMoney()。

//getter for total monetary amount, returned as a double
public double getMoney() {
  return this.dollars + (this.cents/100);
}

You getter method should return the instance variable directly. 您的getter方法应直接返回实例变量。 You were trying to create the new object and then trying to return them. 您试图创建新对象,然后尝试返回它们。 For eg: 例如:

//getter for dollars
public int getDollars(){
    return new Money(dollars);
}

Should be 应该

//getter for dollars
public int getDollars(){
    return this.dollars;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM