我已经“完成”了一个将摄氏温度转换为华氏温度的程序,反之亦然,这是典型的初学者的东西。
但是,即使不满足条件,我的 if 语句也总是会激活,并且我几乎肯定我有正确的 != 语法,因为它与字符串相关,但程序仍然打印 if 语句的打印行,无论我输入的内容。
import java.util.Scanner;
public class TemperatureConverter {
public static void main(String[] args) {
double temp = 0.0;
Scanner in = new Scanner(System.in);
System.out.printf("Please enter the type of temperature conversion you need to perform: ");
String type = in.nextLine();
if (!type.equals("F") || !type.equals("f") || !type.equals("C") || !type.equals("c")){
System.out.println("Invalid conversion, must supply either C or F, program will exit");
System.exit(0); }
switch (type) {
case "F":
System.out.printf("\nPlease enter the temperature to be converted to Celsius: ");
temp = in.nextDouble();
double fToC = (temp - 32.0) * 5.0 / 9.0;
System.out.printf ("\nThe equivalent temperature in Celsius is %.3f\n", fToC);
break;
case "f":
System.out.printf("Please enter the temperature to be converted to Celsius: ");
temp = in.nextDouble();
fToC = (temp - 32.0) * 5.0 / 9.0;
System.out.printf ("\nThe equivalent temperature in Celsius is %.3f\n", fToC);
break;
case "C":
System.out.printf("Please enter the temperature to be converted to Fahrenheit: ");
temp = in.nextDouble();
double cToF = (temp * 9.0 / 5.0) + 32;
System.out.printf ("\nThe equivalent temperature in Fahrenheit is %.3f\n", cToF);
break;
case "c":
System.out.printf("Please enter the temperature to be converted to Fahrenheit: ");
temp = in.nextDouble();
cToF = (temp * 9.0 / 5.0) + 32;
System.out.printf ("\nThe equivalent temperature in Fahrenheit is %.3f\n", cToF);
break;
}
}
}
最佳答案
!type.equals("F") || !type.equals("f")
这始终是正确的。为什么?这意味着“如果类型不是 F 或类型不是 f”。分三种情况:
- 类型等于“F”,但类型不等于“f”。
假||真==真
- 类型不等于“F”,而类型等于“f”。
真||假==真
- 类型不等于“F”,且类型不等于“f”。
真||真==真
如果类型同时为“f”和“F”,则为 false,这是不可能的。
您想使用 &&
而不是 ||
。或者,继续使用 ||
,但移动 !
,如下所示:
if (!(type.equals("F") || type.equals("f") || type.equals("C") || type.equals("c")))
这可能更接近您编写 if 语句时的想法。
此外,您可以使用 equalsIgnoreCase 来缩短长度,而不是同时检查大写和小写版本。
关于java - If 语句比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21923836/