0
What is wrong with my code? it should print according to our input
import java.util.Scanner; public class Program { enum Rank { SOLDIER, SERGEANT, CAPTAIN } public static void main(String[] args) { Scanner rangIn = new Scanner(System.in); String beirt = rangIn.next(); Rank a = Rank.beirt; switch(a) { case SOLDIER: System.out.println("Soldier says hi!"); break; case SERGEANT: System.out.println("Sergeant says Hello!"); break; case CAPTAIN: System.out.println("Captain says Welcome!"); break; } } }
1 Antwort
+ 1
The following statements...
String beirt = rangIn.next();
Rank a = Rank.beirt;
... are not valid. You can't convert a string to an enum type directly.
You could do it this way:
import java.util.Scanner;
public class Program {
enum Rank {
SOLDIER,
SERGEANT,
CAPTAIN
}
public static void main(String[] args) {
Scanner rangIn = new Scanner(System.in);
String beirt = rangIn.nextLine();
Rank a;
switch(beirt.toLowerCase()) {
case "soldier" :
a = SOLDIER;
break;
case "sergeant":
a = SERGEANT;
break;
case "captain":
a = CAPTAIN;
break;
}
switch(a) {
case SOLDIER:
System.out.println("Soldier says hi!");
break;
case SERGEANT:
System.out.println("Sergeant says Hello!");
break;
case CAPTAIN:
System.out.println("Captain says Welcome!");
break;
}
}
}