0

I am writing a program which will take a list of temps and days and implement the list using an array of object. each object will store the temp(double) and day(string). then we need to sort the objects and output them. I created my first class(DailyTemperature) with the two variables, get/set methods, and a constructor. Now when I go to create my second class(DailyTemperatureList) with the ArrayList in it I get an error when trying to add to the list the error says "no suitable method found for add(java.lang.String,double) method java.util.ArrayList.add(int,DailyTemperature) is not applicable (actual argument java.lang.String cannot be converted to int by method invocation conversion) method java.util.ArrayList.add(DailyTemperature) is not applicable actualy and formal lists differ in length.

I assume its because I am trying to use variables from the DailyTemperature class.but when i extend it i get an error saying constructor DailyTemperature in class DailyTemperature cannot be applied to given types. I am not sure why. Am i not supposed to be extending and perhaps do something else?

Here is my code:

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class DailyTemperature 
{
     //variables
    private double temperature;
    private String day;

    //getTemp & setTemp methods
    public double getTemp()
    {
      return temperature;
    }

    public void setTemp(double newTemp)
    {
      temperature = newTemp;
    }

    //getDay & setTEmp methods
    public String getDay()
    {
      return day;
    }

    public void setDay(String newDay)
    {
      day = newDay;
    }


    public DailyTemperature(String day, double temperature) {

      this.day = day;
      this.temperature = temperature;
    }


}



import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class DailyTemperatureList extends DailyTemperature
{
    public static void main (String [] args) {


    ArrayList<DailyTemperature> dailytemps = new ArrayList<DailyTemperature>();

    dailytemps.add("Mon", 78.1);
}
}
4

2 回答 2

2

没有 DailyTemperatureList 扩展 DailyTemperature。这不是继承的用途,因为某物的集合不是某物。您的继承没有通过“is-a”测试;例如,大学班级的学生不是个别学生的更具体的概念。而是让第一个类包含第二个类的 ArrayList,或者 ArrayList<DailyTemperature>.

此外,ArrayList 有一个 add 方法,它接受一个参数,这里是 DailyTemperature 对象,或者接受一个 int 和一个对象,但不接受 String 和一个对象的方法。

我还会让 DailyTemperature 实现Comparable<DailyTemperature>接口,以便可以轻松地对列表进行排序。

于 2013-10-05T23:59:23.897 回答
2

dailytemps是一个ArrayListDailyTemperature因此,在添加时,您需要添加一个实例DailyTemperature

dailytemps.add(new DailyTemperature("Mon", 78.1));

目前已实现,DailyTemperatureList不需要扩展DailyTemperature.

于 2013-10-05T23:59:51.790 回答