java - Java中的变量无法识别
问题描述
对于作业,我正在创建一个命令行程序来将输入的温度从摄氏 (C) 更改为华氏 (F),反之亦然。该程序运行良好,直到用户输入临时类型(C/F),然后它似乎无法识别用户输入。我做错了什么?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the temperature:"); //Prompts user for temperature
String temp = input.nextLine(); //Allows user to input temp data
double tempDouble = Double.parseDouble(temp); //Changes input from string to double
System.out.println("Is " + temp + " degrees in Celsius or Fahrenheit? (Enter C or F):"); //Prompts user for type of temp
String type = input.nextLine(); //Allows user to input temp type
if (type == "C") { //Checks if temp is Celsius
double tempF = 0;
tempF = (tempDouble * 1.8) + 32; //Converts temp to Fahrenheit
System.out.println(tempDouble + "C equals " + tempF + "F."); //Displays conversion of C to F
//Tf = Tc * 1.8 + 32
} else if (type == "F") { //Checks if temp is Fahrenheit
double tempC = 0;
tempC = (tempDouble - 32) / 1.8; //Converts temp to Celsius
System.out.println(tempDouble + "F equals " + tempC + "C.");
//Tc = (Tf - 32) / 1.8
}
System.out.println("Incorrect input for Celsius or Fahrenheit"); //Tells user they didn't input C or F correctly
}
解决方案
代码有两个问题
- 您正在检查对象相等性而不是对象的值。用户 String.equals 方法。
- if-else 块的构造是错误的,它总是会打印“Incorrect input for Celsius or Fahrenheit”。
这是正确的 -
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the temperature:"); //Prompts user for temperature
String temp = input.nextLine(); //Allows user to input temp data
double tempDouble = Double.parseDouble(temp); //Changes input from string to double
System.out.println("Is " + temp + " degrees in Celsius or Fahrenheit? (Enter C or F):"); //Prompts user for type of temp
String type = input.nextLine(); //Allows user to input temp type
if ("C".equals(type)) { //Checks if temp is Celsius
double tempF = 0;
tempF = (tempDouble * 1.8) + 32; //Converts temp to Fahrenheit
System.out.println(tempDouble + "C equals " + tempF + "F."); //Displays conversion of C to F
//Tf = Tc * 1.8 + 32
} else if ("F".equals(type)) { //Checks if temp is Fahrenheit
double tempC = 0;
tempC = (tempDouble - 32) / 1.8; //Converts temp to Celsius
System.out.println(tempDouble + "F equals " + tempC + "C.");
//Tc = (Tf - 32) / 1.8
}else{
System.out.println("Incorrect input for Celsius or Fahrenheit"); //Tells user they didn't input C or F correctly
}
}
推荐阅读
- django - 使用多对多关系更改 Django 模型的主键
- optimization - 从 N 组中找到 k 组值的算法,使得 k 组中唯一值的数量最大化
- vue.js - Vue.js - 努力让 DatePicker 工作的组件
- asp.net - AngularJs如何从ASP.MVC5下载文件传递参数
- javascript - 如何使用 SASS 动态切换颜色主题?
- java - io.reactivex.exceptions.UndeliverableException:Caused by: ZonedDateTime; - 如何在 18 API 版本上使用 ZonedDateTime?
- python - 如何使用 Python 验证管道分隔文件中值的双引号?
- bash - bash 后缀输出到控制台的问题
- dart - 文本光标句柄保持蓝色
- docker - FROM 中的 Dockerfile 私有父镜像规范