Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试使用.equals给变量赋值时出现错误消息_Java_Variables_Joptionpane_Initializing - Fatal编程技术网

Java 尝试使用.equals给变量赋值时出现错误消息

Java 尝试使用.equals给变量赋值时出现错误消息,java,variables,joptionpane,initializing,Java,Variables,Joptionpane,Initializing,我想把温度、湿度和阳光的值相加,但我不知道为什么它说“阳光”变量没有声明。我希望它能够工作,这样当用户输入“是”时,sunshine就会被设置为25,如果他们输入“否”,sunshine就会被设置为-25。谢谢 int temperature; double humidity; int sunshine; String temp; double rating; temp = JOptionPane.showInputDialog(null, "What temperatur

我想把温度、湿度和阳光的值相加,但我不知道为什么它说“阳光”变量没有声明。我希望它能够工作,这样当用户输入“是”时,sunshine就会被设置为25,如果他们输入“否”,sunshine就会被设置为-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;

您没有告诉用户对sunshine问题键入“是”或“否”,也没有检查用户是否键入了这两个值。如果我既不键入“是”也不键入“否”,那么sunshine变量将在分配任何值之前被使用

您可以通过以下方法消除症状:

int sunshine = 0;
但这并不能解决问题

你应该:

1) 指示用户键入“是”或“否”

2) 检查用户是否键入“是”或“否”,并询问问题,直到键入正确的值

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;

如果温度既不是“是”也不是“否”,那么当您到达该行时,
sunshine
将是什么
额定值=温度+湿度+阳光。将减速度更改为
int=0
我强烈怀疑它并没有说
sunshine
没有被声明-相反,它会抱怨
sunshine
没有被明确指定。如果
temp
不等于“yes”或“no”,则不能为其赋值。良好的编码实践是在常量上使用.equals(“yes”,“no”)。如果我们假设这是一个二进制选择,那么
else
似乎是合适的。