gpt4 book ai didi

java - 尝试使用 .equals 为变量赋值时出现错误消息

转载 作者:行者123 更新时间:2023-12-02 10:44:53 25 4
gpt4 key购买 nike

我想将温度、湿度和阳光的值相加,但我不知道为什么它说“阳光”变量没有声明。我希望它能够工作,以便当用户输入“yes”时,sunshine 被设置为 25,如果他们输入 no,则它被设置为 -25。谢谢!

  int temperature;
double humidity;
int sunshine;
String temp;
double rating;

temp = JOptionPane.showInputDialog(null, "What temperature is it outside?");
temperature = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog(null, "What percentage of humidity is there?");
humidity = Double.parseDouble(temp);
temp = JOptionPane.showInputDialog(null, "Is it cloudy out?");
if (temp.equals("yes"))
sunshine = 25;
if (temp.equals("no"))
sunshine = -25;

rating = temperature + humidity + sunshine;

最佳答案

您还没有告诉用户对阳光问题输入"is"或“否”,并且您没有检查以确保用户输入了任一值。如果我不输入"is"或“否”,则在向阳光变量分配任何值之前将使用它。

您可以通过以下方式消除症状

int sunshine = 0;

但这并不能解决问题。

你应该:

1) 指示用户输入"is"或“否”。

2) 检查用户是否输入了"is"或“否”并提出问题,直到输入正确的值

3) 为了获得更好的形式,请使用 if/else 语句。

这是一个新的代码片段:

temp = JOptionPane.showInputDialog(null, "What temperature is it outside?");
temperature = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog(null, "What percentage of humidity is there?");
humidity = Double.parseDouble(temp);
temp = "";
while (!temp.equals("yes") && !temp.equals("no")) {
temp = JOptionPane.showInputDialog(null, "Is it cloudy out? Type 'yes' or 'no' ");
}
if (temp.equals("yes"))
sunshine = 25;
else
sunshine = -25;

rating = temperature + humidity + sunshine;

关于java - 尝试使用 .equals 为变量赋值时出现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52656808/

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