Couple of problems with your code:
- Enum declarations as per the specification can't be local i.e. placed in a method. Move the enum declaration either outside of your TemperateConverter class or either outside the main() method.
- Why C, c and F, f (BTW, you have got both capital F) when in the end both C/c stand for the same thing? Just declare two members for your enum, C and F and you should be good to go.
- You can't directly convert between enum and strings, which is what you seem to be doing in TempType = in.nextChar() (which is BTW incorrect since TempType is a type name). Use valueOf() method of an enum which returns the enum object from string representation. Make sure you account for the case sensitivity of enums by passing in a stripped and upper-case version of the user entered string.
- No error handling when the user enters "A" as the temperature.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
OK, my point was:
The representation of C or F for the user can change based on how it is presented to the user. E.g. the user can enter "C" for celsius and tomorrow might want to enter "CELSIUS" etc. As far as your domain (problem statement) representation is concerned, there are only two temperature types (C and F). It is *your* responsibility (or the responsibility of the presentation/user interface) layer to convert the user entered value to C or F temp type i.e. how the user perceives Celsius or Fahrenheit shouldn't change how your *application* perceives the temp type.
To talk in terms of code (not compiled):
enum TempType { C, F }
public class Test {
public static void main(final String [] args) {
String line = scanner.nextLine().trim();
// Account for case sensitivity here ---v
// instead of doing it in enums
if("C".equalsIgnoreCase(line)) {
TempType t = TempType.valueOf(
} else {
System.err.println("Invalid temp type passed: one of 'c' or 'C' expected (without quotes)");
}
}
}
The advantage here is that for a big application (though your application isn't ATM, but we are here to learn, right?) all usages of this TempType won't be burdened by checking for two different types (c and C) for something which is the same i.e. Celsius temperature type. This is a big win in terms of expressiveness and maintainability.
To move a step above, you can code the same logic in the enum type by extending it to handle creation of TempType from string "c", "C", "CELSIUS" etc. rather than having the logic in your driver (main method) code. But that would come later; make sure you understand what has been posted above along with realizing why having two celsius representation would be a bad idea. Ask back if you still have questions.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734