R
R
Ro Gry2021-11-14 15:15:41
Java
Ro Gry, 2021-11-14 15:15:41

How to make enum.valueOf() return the desired value?

Hello. I have three classes: Motorcycle, MotorcycleManager (main), Color (enum)

In the Motorcycle class I have a toString() method and variables are set:

public class Motorcycle {
  
  String name;
  int yearOfProduction;
  int price;
  int weight;
  Color color;
  String engineType;
  boolean isReadyToDrive;	
  
  public Motorcycle(String name, int yearOfProduction, int price, int weight, Color color, String engineType,
      boolean isReadyToDrive) {
    this.name = name;
    this.yearOfProduction = yearOfProduction;
    this.price = price;
    this.weight = weight;
    this.color = color;
    this.engineType = engineType;
    this.isReadyToDrive = isReadyToDrive;
  }



  @Override
  public String toString() {
    return "Motorcycle [name=" + name + ", yearOfProduction=" + yearOfProduction + ", price=" + price + ", weight="
        + weight + ", color=" + color + ", engineType=" + engineType + ", isReadyToDrive=" + isReadyToDrive
        + "]";
  }
}


The MotorcycleManager class is my main, I start it from it using the constructor:
public class MotorcycleManager {

  public static void main(String[] args) {
    
    Motorcycle suzuki = new Motorcycle("Suzuki GSX-R1000", 2021, 16000, 600, Color.BLACK, "diesel", true);
    Motorcycle yamaha = new Motorcycle("Yamaha FZ1", 2007, 9000, 700, Color.ORANGE, "gas", false);
    
    
    System.out.println(suzuki);
    System.out.println(yamaha);
  }
}


The enum Color class contains constants:
public enum Color {
  
  WHITE, GREEN, BLACK, BLUE, ORANGE
  
}


I need to modify the code so that the color is displayed in the console without caps, using the enum.valueOf(), String.toUpperCase(), String.replace methods.

Please advise how to achieve this and / or where to read about it so that it is clear and clearly written.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BorLaze, 2021-11-14
@BorLaze

enum Color {
    WHITE("white"), BLACK("black");

    private final String color;

    Color(String color) {
        this.color = color;
    }


    @Override
    public String toString() {
        return color;
    }
}

Color c = Color.WHITE;
System.out.println(c);

The result is white
-----
I don't know if I understood your question correctly, but, in any case, the direction is

I
Iskak, 2021-11-15
@Iskak9

You override toString and that's it.

public enum Color {
    WHITE, GREEN, BLACK, BLUE, ORANGE;
    
    @Override
    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question