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; } } }

22nd Jul 2017, 3:57 PM
Győrfy Balázs
Győrfy Balázs - avatar
1 ответ
+ 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; } } }
22nd Jul 2017, 4:40 PM
Hassie
Hassie - avatar