gpt4 book ai didi

java - 如何在 if 语句中使用键盘上的字符 [Java]

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:37 27 4
gpt4 key购买 nike

我的代码有点问题。我需要将温度从摄氏度转换为华氏度,反之亦然,用户选择“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.");
}

最佳答案

您可以使用 Scanner 读取您的输入,然后调用查看它是否等于“C”或“F”

例如,

Scanner x = new Scanner(System.in);

String choice = x.nextLine();

if (choice.equals("F") || choice.equals("f")) { 
blah blah blah
}
if (choice.equals("C") || choice.equals("c")) {
blah blah blah
}

关于java - 如何在 if 语句中使用键盘上的字符 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19385882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com