gpt4 book ai didi

java - 初学者做while循环错误

转载 作者:行者123 更新时间:2023-12-02 04:57:49 25 4
gpt4 key购买 nike

我不明白为什么我的代码的最后一行抛出错误“cont无法解析为变量”基本上我需要在循环中将华氏度转换为摄氏度,以防他们想要转换多个温度。

如果他们说 c 或 f 以外的内容,我还需要让程序要求他们重新输入温度类型,而不要求他们重新输入数字

这是我的两个问题,这是我的代码,谢谢!

 //Jonathan Towell
//This program will convert temperatures from celsius to Fahrenheit
import javax.swing.JOptionPane;
public class FarenheitOrCelsius
{

public static void main(String[] args)
{
do
{
double temp = Double.parseDouble(JOptionPane.showInputDialog("Enter the temperature to be converted"));
String ver = JOptionPane.showInputDialog("Is that temperature in celsius or fahreneheit?\n" + "Enter C or F");

if (ver.toLowerCase().contains("c")) //If C is entered convert to fahrenheit
{
double result = Math.round(((9 * (temp)/5) + 32));
JOptionPane.showMessageDialog(null, "You entered " + temp + " degrees celsius.\n" + "That temperature in fahrenheit is " + result);
int cont = Integer.parseInt(JOptionPane.showInputDialog("Do you want to convert another temperature?", JOptionPane.YES_NO_OPTION));
}
else if (ver.toLowerCase().contains("f")) //If f is entered covert to celsius
{
double result = Math.round((5 *(temp - 32)/9)); //Math equation for coversion from F to C
JOptionPane.showMessageDialog(null, "You entered " + temp + " degrees fahrenheit.\n" + "That temperature in celsius is " + result);
int cont = Integer.parseInt(JOptionPane.showInputDialog("Do you want to convert another temperatuer?", JOptionPane.YES_NO_OPTION));
}
else JOptionPane.showMessageDialog(null, "Invalid Option.\n Only enter C or F.");
{
System.exit(0);
}

} while (cont = JOptionPane.YES_OPTION);
}
}

最佳答案

cont 是在内部作用域中声明的,因此不可用于 while 循环。您需要在 do 语句之前声明它:

int cont = JOptionPane.NO_OPTION;
do {
...
cont = Integer.parseInt( ...

...
cont = Integer.parseInt( ...
} while (cont == JOptionPane.YES_OPTION);

请注意,您还需要使用双 =while 测试中进行比较。

关于java - 初学者做while循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28597802/

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