在方法中使用另一个类的方法

时间:2014-10-23 01:16:14

标签: java methods inner-classes

更新:我的问题与主构造函数有关。我没有正确初始化类实例,所以java指出我的问题是关于我的方法所在的行。换句话说,我的方法是问题,因为他们没有没有正确初始化。

我有3节课。第一个设置Date,第二个设置发票并使用Date类的2个实例。第三个类使用main()中第二个类的1个实例。

我的问题是,我正在尝试在第二类中使用setDates方法,该方法使用第一类实例及其方法,但它不起作用。

这是Java错误:       线程“main”java.lang.NullPointerException中的异常         在InvoiceDate.setDatesFromUser(InvoiceDate.java:57)         在Thirdclss.main(Thirdclss.java:7)

我想了解如何修复代码或其他方法来做同样的事情,以便它正常工作。

以下是3个类的示例代码。如果我没有明确说明我的问题,请发表评论。

//first class that set date

public class OurDate {
    private int day;

    public OurDate() {
        day = 1;
    }

    public OurDate(int d ){
        day = d;
    }

    public void inputDay( ) {
        Scanner keyboard = new Scanner (System.in);
        System.out.print("Enter a day(1-31): ");
        day = keyboard.nextInt();
    }// end inputday

    public int calcTotalDay() {
        int x = ((year*365)+(month*30)+day);
        return  x;
    }
}

这是第二节课:

public class InvoiceDate {
    private double invoiceAmount;
    private OurDate todayDate;
    private OurDate invoiceDate;

    public InvoiceDate (double invoiceAmount,OurDate todayDate, OurDate invoiceDate){
        this.invoiceAmount = invoiceAmount;
        this.todayDate = todayDate;
        this.invoiceDate = invoiceDate;
    }

    public void setDatesFromUser (){  //HERE is where I stuck
        todayDate.inputDay();        //inputDay is method in OurDate class
        invoiceDate.inputDay();
    }

    public void calculateInvoice(){
        int DayAmt = todayDate.calcTotalDay()  -  invoiceDate.calcTotalDay() ;
        invoiceAmount = (DayAmt/30)*5; 
    }
}

第三个类只从第二个类和主构造函数中获取一个实例。

 //Third Class
 public class Thirdclss  {
public static void main(String[] args){
    System.out.println("Welcome");
    InvoiceDate invDate = new InvoiceDate(10, null, null);
    invDate.setDatesFromUser();
    invDate.calculateInvoice();

}

}

3 个答案:

答案 0 :(得分:0)

您需要在InvoiceDate中初始化成员:

public class InvoiceDate {
    private double invoiceAmount;
    private OurDate todayDate = new OurDate();
    private OurDate invoiceDate = new OurDate();

答案 1 :(得分:0)

问题在于如何在第三个类中获取InvoiceDate的实例,请尝试:

//Third Class
public class Thirdclss  {
    public static void main(String[] args) {
        System.out.println("Welcome");
        InvoiceDate invDate = new InvoiceDate(10); //this line had the issue
        invDate.setDatesFromUser();
        invDate.calculateInvoice();
    }
}

更新

在构造函数中,您传递null todayDateinvoiceDate删除这些并更改第二个类:

public class InvoiceDate {
    private double invoiceAmount;
    OurDate todayDate = new OurDate();
    OurDate invoiceDate = new OurDate();

    public InvoiceDate (double invoiceAmount) {
        this.invoiceAmount = invoiceAmount;
    }
    //rest of class

答案 2 :(得分:0)

public InvoiceDate(){
    minutesPurchased = 0.00;
    todayDate = new OurDate();    //This is the how I should initialize 
    invoiceDate = new OurDate();  //instances from class 1.This is the solution...
}