How can I get this switch statement to work using a scanner?

无人久伴 提交于 2019-12-03 14:47:38

You need to use charAt. Scanner.next() method returns String not char so you will need to convert String to char

letter = kb.next().charAt(0);

You can better create a Map<Character, String> to save yourself from writing 26 cases in switch. This way you just have to get the String for a particular character.

Map<Character, String> mapping = new HashMap<Character, String>();
mapping.put('a', "Alpha");
mapping.put('b', "Beta");
..  And so on..

Of course you have to take the burden of initializing the Map, but it will be better than a Mess of switch - case

Benefit is that, you can also populate the Map from some file later on.

Then when you read character from scanner, use charAt(0) to fetch the first character, because Scanner.next() returns a String: -

letter = kb.next().charAt(0);

// Fetch the Phonetic for this character from `Map`
phonetic = mapping.get(letter);
String letter;
String phonetic;
Map<String,String> codes = new HashMap<String,String>();
codes.put("A","Alpha");
codes.put("B","Bravo");
codes.put("C","Charlie");
codes.put("D","Delta");
    // not showing all assignments to make it shorter
codes.put("W","Whiskey");
codes.put("X","X-Ray");
codes.put("Y","Yankee");
codes.put("Z","Zulu");

Scanner kb = new Scanner(System.in);

System.out.print("Please enter a letter: ");
letter = kb.next().toUpperCase();

phonetic = codes.get(letter);

if (phonetic == null) {
    System.out.println("bad code : " + letter);
} else {
    System.out.println("Phonetic: " + phonetic);
}

The Scanner.next() method returns a String, not a char, so you need to get the first character of that String using String.charAt(...) before comparing it to chars.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!