1

i tried to use an enum for my first time. For some Tests i want to override the toString method of my enum and return a String with the chosen enum.

Heres my code so far:

@Override
public String toString()
{
    return "Fahrzeuge{" +
            switch(this)
            {
                case MOTORAD: "1"; break;
                case LKW: "2"; break;
                case PKW: "3"; break;
                case FAHRRAD: "4"; break;
            }
            +
            "typ:" + this.typ +
            ", ps:" + this.ps +
            ", reifen:" + this.reifen +
            ", gewicht:" + this.gewicht +
            "}";
}

IntelliJ underline my cases and tell me the following: "Not a Statement" => I guess this makes sense, if it's not allowed to build a String with a switch - case.

So far so good, but it seem's to be impossible to return a String which is build through a switch case, or did i make a mistake at my return? Any other options to return the chosen enum? I could add an attribute that hold my chosen enums name, but i though i could do this a bit simpler.

Thanks for help

Óscar López
  • 232,561
  • 37
  • 312
  • 386
lain91
  • 11
  • 4
  • "*So far so good, but it seem's to be impossible to return a String which is build through a switch case*" - How do you come to this conclusion? Do you get a compiler exception? A runtime exception? If so, please include the compiler error / stack trace. --- Two remarks: - Have you taken a look at [`Enum#ordinal()`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Enum.html#ordinal())? - You should get used to write your code in english, at least as long as there are acceptable translations for your domain (`type`, `tires`, `hp`, `weight`, ...) – Turing85 Sep 07 '19 at 11:59
  • IntelliJ underline my cases and tell me the following: "Not a Statement" Guess this makes sense, if it is not possible to return a switch case generated String. – lain91 Sep 07 '19 at 12:03
  • ... Please include the compiler error by [edit]ing your question. One more remark: The code as-is does not seem extensible, thus violating the [Open-Closed Principle](https://en.wikipedia.org/wiki/Open–closed_principle). I would suggest to transform the `Enum` into a class. Together with some [Builders](https://en.wikipedia.org/wiki/Builder_pattern) you could achieve the same behaviour, but more extensible (e.g. your list is missing E-Scooters and tanks ) – Turing85 Sep 07 '19 at 12:05
  • And two more: - in your `toString()`-implementation, you start the `String` with `"Fahrzeuge"` (`"vehicles"`, plural), but the `String` actually represents only ONE `"Fahrzeug"` (`"vehicle"`). - Attribute `reifen` (`tires`): this is too generic. Is this the type of tire? The brand? The amount? Be more specific, e.g. in your case `"anzahlReifen"` (`"numOfTires"`). – Turing85 Sep 07 '19 at 12:12
  • It's not important how much sense the names do. This code is just for me and some coding practice. Thanks so far, but i can't see a solution for my question here. – lain91 Sep 07 '19 at 12:18
  • Well.. those are comments, not answer, aren't they ? [Oscar answered your question already](https://stackoverflow.com/a/57833576/4216641). I question your overall design, i.e. the usage of an `Enum` in this way, and reviewed your code. – Turing85 Sep 07 '19 at 12:20
  • 1
    Why does your enum have fields for everything except the number? Just add it and you'll be fine. Also, it's "Motorrad" with two "r"s. – daniu Sep 07 '19 at 12:25

2 Answers2

1

It's possible to return the value of a switch statement starting with Java 12, as per JEP 325. Check your version of Java, if it's anything less than 12 then you can't use switch like that and you'll have to resort to first saving the intended value in a local variable. My point is, if your version of java is older than 12, then you have to do this:

String num = "";
switch (this)
{
    case MOTORAD:
        num = "1";
        break;
    case LKW:
        num = "2";
        break;
    case PKW:
        num = "3";
        break;
    case FAHRRAD:
        num = "4";
        break;
}

return "Fahrzeuge{" + num +
            "typ:" + this.typ +
            ", ps:" + this.ps +
            ", reifen:" + this.reifen +
            ", gewicht:" + this.gewicht +
            "}";

But if you have Java 12 (or above) installed, then you can do this (notice the different syntax!):

return "Fahrzeuge{" +
            switch (this)
            {
                case MOTORAD -> "1";
                case LKW     -> "2";
                case PKW     -> "3";
                case FAHRRAD -> "4";
            }
            + "typ:" + this.typ +
            ", ps:" + this.ps +
            ", reifen:" + this.reifen +
            ", gewicht:" + this.gewicht +
            "}";

And do notice that if the numbers correspond to the order in which the enum values were declared, you can simply use ordinal():

return "Fahrzeuge{" + this.ordinal() +
            "typ:" + this.typ +
            ", ps:" + this.ps +
            ", reifen:" + this.reifen +
            ", gewicht:" + this.gewicht +
            "}";
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    For reference: this JEP is part of [Project Amber](https://openjdk.java.net/projects/amber/) (can't wait for its GA) – Turing85 Sep 07 '19 at 12:14
  • The switch(this) works well for me in any other method. The Problem ist, that i can't build my return String with a switch - case to get a part of the String. – lain91 Sep 07 '19 at 12:23
  • Yes, that's what my answer states: you can't use it as part of an expression (such as `return`) in older versions of Java. To be sure: what version are you using? – Óscar López Sep 07 '19 at 12:24
  • @lain91 as was stated, the default switch is a [statement](https://en.wikipedia.org/wiki/Statement_(computer_science)), not an [expression](https://en.wikipedia.org/wiki/Expression_(computer_science)). Statements do not have values, thus you cannot use them on the right side of an assignment. – Turing85 Sep 07 '19 at 12:24
  • @ÓscarLópez ah okay, now i get it. thanks I use the default settings at IntelliJ which is SDK - 12 (guess this is Java - 12 ? ) – lain91 Sep 07 '19 at 12:32
  • @lain91 check all my answer, jut try the three options. If the second one works, then yes, you have installed Java 12 :) . But personally, I'd prefer to use the third option. – Óscar López Sep 07 '19 at 12:37
0

I think you really don't need the switch Statement because the superclass of the enum already knows the name of your "type":

@Override
public String toString()
{
    return "Fahrzeuge: " + super.toString() +
            ", ps:" + this.ps +
            ", reifen:" + this.reifen +
            ", gewicht:" + this.gewicht;
}

Simply call the toString() method of the super class and you get the string value of your currently selected enum-type. You even can delete your type string.

BlackCat
  • 160
  • 2
  • 8
  • Thanks, this is the solution i was looking for! But i also learned that a switch should't be codet on the right side of an expression :) – lain91 Sep 07 '19 at 12:51