如何在if语句中使用键盘字符[Java]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19385882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use char from keyboard in if statement [Java]
提问by user2883232
I am having a bit of a problem with my code. I need to make a temperature conversion from Celsius to Fahrenheit and vice-versa with the user choosing either "F" or "C" (lower or upper case) but cannot seem to figure out how to do it properly. I don't know how to have it recognize that the variable is supposed to be entered via the keyboard.
我的代码有点问题。我需要将摄氏温度转换为华氏温度,反之亦然,用户选择“F”或“C”(小写或大写),但似乎无法弄清楚如何正确转换。我不知道如何让它识别出应该通过键盘输入的变量。
Scanner Keyboard = new Scanner(System.in);
System.out.println("Type C to convert from Fahrenheit to Celsius or" +
"F to convert from Celsius to Fahrenheit.");
char choice = Keyboard.nextLine().charAt(0);
//Get user input on whether to do F to C or C to F
if (choice == F) //Fahrenheit to Celsius
{
System.out.println("Please enter the temperature in Fahrenheit:");
double C = Keyboard.nextDouble();
double SaveC = C;
C = (((C-32)*5)/9);
System.out.println(SaveC + " degrees in Fahrenheit is equivalent to " + C + " degrees in Celsius.");
}
else if (choice == C)
{
System.out.println("Please enter the temperature in Celsius:");
double F = Keyboard.nextDouble();
double SaveF = F;
F = (((F*9)/5)+32);
System.out.println(SaveF +" degrees in Celsius is equivalent to " + F + " degrees in Fahrenheit.");
}
else if (choice != C && choice != F)
{
System.out.println("You've entered an invalid character.");
}
采纳答案by Boann
When comparing with the choice
variable your F and C characters should be wrapped in single quotes to make them character literals. Use ||
(meaning 'or') to test for upper or lower case. I.e.,
当与choice
变量比较时,你的 F 和 C 字符应该用单引号括起来,使它们成为字符文字。使用||
(意思是“或”)来测试大写或小写。IE,
if (choice == 'F' || choice == 'f')
...
else if (choice == 'C' || choice == 'c')
...
else
...
回答by Kurty
You can use Scanner to read your input and then call to see if it is equal to "C" or "F"
您可以使用 Scanner 读取您的输入,然后调用以查看它是否等于“C”或“F”
For example,
例如,
Scanner x = new Scanner(System.in);
String choice = x.nextLine();
扫描仪 x = 新扫描仪 (System.in);
字符串选择 = x.nextLine();
if (choice.equals("F") || choice.equals("f")) {
blah blah blah
}
if (choice.equals("C") || choice.equals("c")) {
blah blah blah
}