本文介绍了无法从静态上下文引用非静态方法toString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不想要任何代码,只是想要某种指导。我希望保持我的学术诚信;)

Don't want any code, just want some sort of guidance. Would like to keep my academic integrity in tact ;)

我一直都会遇到这个恼人的错误。我需要为每个Room实例调用toString方法。有什么建议?如果可能的话,我希望在2小时内给出答案。

I keep getting that annoying error. I need to call the toString method for each Room instance. Any suggestions? I would prefer an answer within 2 hours if at all possible.

public class Hotel
{
    //constant
    public static final int NUM_ROOMS = 20;

    //variables
    public Room[] theRoom;
    public String name;
    public int totalDays;
    public double totalRate;
    public int singleCount;
    public int doubleCount;
    public int roomsRented;
    public int NOT_FOUND;

    public Hotel(String newName) {
        name = newName;
        Room[] Rooms = new Room[NUM_ROOMS];
    }

    public double getTotalRentalSales() {
        return totalRate + roomsRented;
    }

    public double getAvgDays() {
        return roomsRented/totalDays;
    }

    public double getAvgRate() {
        return totalRate/roomsRented;
    }

    public int getSingleCount() {
        return singleCount;
    }

    public int getDoubleCount() {
        return doubleCount;
    }

    public String printRentalList() {
        System.out.println("Room Information: " + Room.toString());
    }
}


推荐答案

你不应该尝试在Room类上调用 toString(),而是在Room 对象上调用。在该方法中,使用for循环遍历房间数组并打印通过调用 toString()返回的String,以获取数组中保存的每个Room对象,因为这就是它看起来你的方法应该这样做。

You shouldn't try to call toString() on a Room class but rather on a Room object. In that method, loop through the array of rooms with a for loop and print the String returned by calling toString() for each Room object held in the array since this is what it looks like your method should do.

例如

System.out.println("All Foos held here include: ");

// using a "for-each" loop, assuming an array called fooArray that holds Foo objects
for (Foo foo: fooArray) {
   System.out.println(foo);
}

您显然必须更改代码的类型和变量名称。

You will obviously have to change the types and variable names for your code.

编辑2:虽然你必须使用标准for循环,而不是for-each循环,因为你不会循环遍历整个数组,而是会当达到roomsRented计数时退出。

Edit 2: although you will have to use a standard for loop, not a for-each loop, since you won't be looping through the entire array, but rather will quit when roomsRented count is reached.

System.out.println("All Foos held here include: ");

// using standard for loop, assuming an array called fooArray that holds Foo objects
for (int i = 0; i < someMaxNumber; i++) {
   System.out.println(fooArray[i]);
}

这篇关于无法从静态上下文引用非静态方法toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:32
查看更多