1

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

3 回答 3

1

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

例如,

扫描仪 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 
}
于 2013-10-15T16:08:57.483 回答
0

choice变量进行比较时,您的 F 和 C 字符应该用单引号括起来,以使它们成为字符文字。使用||(意思是“或”)来测试大写或小写。IE,

if (choice == 'F' || choice == 'f')
    ...
else if (choice == 'C' || choice == 'c')
    ...
else
    ...
于 2013-10-15T16:09:36.643 回答
0
import java.util.Scanner;

public class conversion {

    public static void main(String[] args) {
        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' || 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' || 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 
            { 
                System.out.println("You've entered an invalid character.");
            } 
    }
    
}
于 2021-12-15T10:33:16.067 回答