如何使用扫描仪使此switch语句正常工作? [英] How can I get this switch statement to work using a scanner?
问题描述
我正在尝试编写一个程序,将字母表中的任何字母(大写或小写)切换为Phontic字母表。例如,如果我输入A或a,我的程序将给我(更改为)Alpha。
我已经对这个和切换语句做了很多研究,但我一直陷入困境。我意识到我不能在扫描仪中使用'char'。但是,当我将'char'更改为'String'时,我的switch语句会混乱(特别是我的代码中的 toUpperCase 会被加下划线。我无法看到我的错误。这就是我所做的远:
I'm trying to write a program that will switch any letter of the alphabet (upper or lower cases) into the Phontic alphabet. For example, If I enter "A" or "a" my program will give me (change it to) "Alpha". I've done so much research on this and switch statements but I keep getting stuck. I've realized that I can't use 'char' in a scanner. However, when I change 'char' into a 'String' my switch statement messes up (specifically the toUpperCase in my code gets underlined. I can't see my mistake. Here's what I've done so far:
import java.util.Scanner;
public class PhoneticTranslate {
public static void main(String[] args) {
char letter;
String phonetic;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter: ");
letter = kb.next();
switch(Character.toUpperCase(letter))
{
case 'A':
phonetic = "Alpha";
break;
case 'B':
phonetic = "Bravo";
break;
case 'C':
phonetic = "Charlie";
break;
case 'D':
phonetic = "Delta";
break;
case 'E':
phonetic = "Echo";
break;
case 'F':
phonetic = "Foxtrot";
break;
case 'G':
phonetic = "Golf";
break;
case 'H':
phonetic = "Hotel";
break;
case 'I':
phonetic = "India";
break;
case 'J':
phonetic = "Juliet";
case 'K':
phonetic = "Kilo";
break;
case 'L':
phonetic = "Lima";
break;
case 'M':
phonetic = "Mike";
break;
case 'N':
phonetic = "November";
break;
case 'O':
phonetic = "Oscar";
break;
case 'P':
phonetic = "Papa";
break;
case 'Q':
phonetic = "Quebec";
break;
case 'R':
phonetic = "Romeo";
break;
case 'S':
phonetic = "Sierra";
break;
case 'T':
phonetic = "Tango";
break;
case 'U':
phonetic = "Uniform";
break;
case 'V':
phonetic = "Victor";
break;
case 'W':
phonetic = "Whiskey";
break;
case 'X':
phonetic = "X-Ray";
break;
case 'Y':
phonetic = "Yankee";
break;
case 'Z':
phonetic = "Zulu";
break;
}
}
}
推荐答案
你需要使用charAt。 Scanner.next()
方法返回字符串
不是字符
所以你需要将 String
转换为 char
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);
这篇关于如何使用扫描仪使此switch语句正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!