Liondancer
Liondancer

Reputation: 16469

printing enum variables and values

I am trying to test enum out but I am currently having a bit of trouble. I want to be able to print out the values but I am not sure how to.

code:

class test2 {
    public enum games {
        COD (3, 49.99), CS (5, 29.99), HL2 (5, 29.99), HALO (5, 49.99);
        int rating;
        float cost;
        games(int rating, float cost) {
            this.rating = rating;
            this.cost = cost;
        }
    }

    public static void main(String[] args) {
        for (games g : games.values()) {
            System.out.println(g +" " + g.rating + " " + g.cost);
        }
    }
}

Upvotes: 0

Views: 77

Answers (3)

Don Roby
Don Roby

Reputation: 41137

Your calls to the enum constructor use the wrong type for the field cost as defined.

You can correct this by changing the field type to double or by passing floats in the calls, i.e., either change

    float cost;
    games(int rating, float cost) {

to

    double cost;
    games(int rating, double cost) {

or change

    COD (3, 49.99), CS (5, 29.99), HL2 (5, 29.99), HALO (5, 49.99);

to

    COD (3, 49.99f), CS (5, 29.99f), HL2 (5, 29.99f), HALO (5, 49.99f);

With either change, your code runs fine.

Upvotes: 2

SerCrAsH
SerCrAsH

Reputation: 450

You must to replace that

float

with

double

And execute your code :)

Upvotes: 1

Leo
Leo

Reputation: 6570

try

COD (3, 49.99f), CS (5, 29.99f), HL2 (5, 29.99f), HALO (5, 49.99f);

default for floating point in java is double ;-)

Upvotes: 1

Related Questions