【问题标题】:The type of the expression must be an array type but it resolved to "Temperature" -JAVA表达式的类型必须是数组类型,但它解析为“温度”-JAVA
【发布时间】:2012-05-10 15:53:45
【问题描述】:

大家好,

所以我创建了一个温度类,它有一个构造函数来产生温度。 温度是 2 个数字 [冷、热] 的数组列表。

    public int hotness;
public int coldness;
public int[] temperature;
public int maxTemperature = 10000;


//Constructor Temperature
public Temperature(int hotness, int coldness) {
    /**
     * A constructor for the Array Temperature
     */
    maxTemperature = getMaxTemperature();
        if(hotness <= maxTemperature && coldness <= maxTemperature)
        temperature[0] = coldness;
        temperature[1] = hotness;
        }

现在我想进入另一个类并使用该对象温度进行一些计算。这是它的代码。

    //Variabels

public int volatility;
private static Temperature temperature;
private static int intrensicExplosivity;

    public static int standardVolatility(){
    if(temperature[0] == 0){
        int standardVolatility = 100 * intrensicExplosivity * (0.10 * temperature[1]);
    }

所以现在我得到了错误:表达式的类型必须是数组类型,但它解析为“温度”

有什么解决办法吗?

我对 Java 很陌生,所以可能只是一些语法错误,但我就是找不到。

提前致谢。 大卫

【问题讨论】:

  • 如果有错误,请贴出异常或错误的堆栈跟踪。

标签: java


【解决方案1】:

而不是

public static int standardVolatility() {
    if(temperature[0] == 0) {

试试

public static int standardVolatility() {
    if(tepmerature.temperature[0] == 0) {
       ^^^^^^^^^^^^

请注意,第二个 sn-p 中的 temperatureTemperature 类型,它本身有一个名为 temperature 的 int 数组。要访问Temperature 对象的temperature 数组,您必须执行temperature.temperature


正如@Marko Topolnik 指出的那样,您可能还想改变

public int[] temperature;

public int[] temperature = new int[2];

为了给两个温度值腾出空间。

【讨论】:

  • 您也可以建议他需要初始化数组(这是他的下一个错误),或者根本不使用数组:)
【解决方案2】:

首先在 Temperature 类中创建 getter 和 setter 方法,然后调用 temperature.getTempertature() 并在第二个类中使用它。

【讨论】:

  • 我改变了你们建议的东西,谢谢你们现在一切正常!!我会给更多的绿色 V 但只能一个:p
【解决方案3】:

tempetureTempeture 类型,它不是一个数组。 您想要的是对象实例中的数组成员temperature(也称为tempature)。

无论如何换行:

if(temperature[0] == 0) 
.
.

与:

if(temperature.tempature[0] == 0)
.
.

我会建议你使用 getter 和 setter,并使用不会让你感到困惑的名称。

【讨论】:

    【解决方案4】:

    你在这里混淆了一些变量。

    在下面的代码块中,temperature 引用了 Temperature 类的一个实例,但您假设它引用了温度数组,它是 Temperature 类的成员。

    public static int standardVolatility() {
        if(temperature.temperature[0] == 0){
            int standardVolatility = 100 * intrensicExplosivity * (0.10 * temperature[1]);
        }
    

    【讨论】:

      【解决方案5】:

      好吧,你的问题就在这里

      private static Temperature temperature;
      if(temperature[0] == 0){
              int standardVolatility = 100 * intrensicExplosivity * (0.10 * temperature[1]);
      }
      

      您将对象用作数组。那是错误的。 相反,请使用 GET 和 set 方法来设置和获取温度。 不要公开所有数据,这对 OO 编程非常不利。使用那些 getter 和 setter。 类似于:if(temperature.getTemperature()==0) etc.

      PS:别忘了用 new 操作符(Temperature temperature = new Temperature(10,30);)初始化对象

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-24
        • 2019-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-16
        • 2016-02-20
        相关资源
        最近更新 更多