Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

java - non-static method toString() cannot be referenced from a static context

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

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());
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

For example

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.

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]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...