0

我在这个 Java 课程中,我基本上是想成为一个优秀的人,但我大部分时间都在试图弄清楚事情并且它不起作用。

我正在创建温度类的 ArrayList。

List<Temperature> templist = new ArrayList<Temperature>();
Temperature t1 = new Temperature ();

for (number of loops user wants) 
{
 templist.add(t1)
}

但是我的温度课程既有数量又有规模。因此,当我显示 t1 时,它看起来像这样

Temperature [degrees=43.0, scale=F]  

我如何使用我的getDegrees()andgetScale()方法来单独提取degreesand scales。我也需要得到一个最小值、最大值和平均值。我知道如何使用 for 循环来做到这一点,但是由于涉及到类的实例,这仍然可能吗?

所以基本上这就是我所拥有的

温度.java

import java.util.Scanner;

/*
 * This class represents a temperature value.
 */
    public class Temperature {

private double degrees;
private char scale;
Scanner s = new Scanner (System.in);



public Temperature (){
this.degrees = 0 ;
this.scale = 'F' ;
    }



public double getDegrees() {
    return degrees;
}

//public double getDegreesF(){
//  return degrees;
//}

public double getDegreesC(Temperature temperature)

{
         if (scale == 'C') 
             return degrees;
         else if (scale == 'F')
           degrees = ((degrees - 32)*(5)/(9));
           return degrees;


}



public void setDegrees(double degrees) {
    this.degrees = degrees;
}

public char getScaleC() {
     scale = 'C';
    return scale;
}



    public void setScale(char scale) {

    while  ((scale != 'C') && (scale !='F') )

       {

        System.out.println("Please enter correct value");
        scale = s.next().charAt(0);
      } 

    this.scale = scale;
}


@Override
public String toString() {
    return "Temperature [degrees=" + degrees + ", scale=" + scale + "]";
}


    }

 Test Temperature.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;




public class TestTempreture {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int numberoftimes = 0 ;


        Scanner s = new Scanner (System.in);

        Temperature t1 = new Temperature ();
        List<Temperature> templist = new ArrayList<Temperature>();

        for (int i = 0; i < numberoftimes; i ++  )

        {

            t1.setDegrees(s.nextInt());
            t1.setScale(s.next().charAt(0));
            templist.add(t1);


        }


        System.out.println(templist.get(0));
4

1 回答 1

0

问题是,ArrayList不知道如何计算minmaxaverage。您可以在主代码中使用循环,也可以使用组合...

public class AllTemps {
    private static final ArrayList<Temperature> temps = new ArrayList<Temperature>();
    private Temperature min = null;

    public AllTemps() { }

    public boolean add(Temperature t) {
        updateMin(t);
        return temps.add(t);
    }

    // Here you would implement any other methods to access the ArrayList that you need

    private void updateMin(Temperature t) {
        if (min == null) {
            min = t;
        } else {
            if(min.getDegrees() > t.getDegrees()) min = t;
        }
    }
}

然后您可以以相同的方式实现计算max,average等。

于 2012-11-15T19:58:12.563 回答