初学者做 while 循环错误

beginner do while loop error

我不明白为什么我的代码的最后一行会抛出错误 "cont cannot be resolved to a variable" 基本上我需要在一个循环中将华氏温度转换为摄氏温度,以防他们想要转换多个温度。

如果他们说的不是 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测试中还需要使用double=来做比较

就像 local 方法变量仅在该方法内可用一样,在一对花括号 {} 内声明的变量的范围仅限于该块只有代码。然而,在块外声明的变量在块内和块外都可用。

所以,在下面的代码中

do {
   int localToDoBlock = 1;
   ...
   localToDoBlock++;
} while (localToDoBlock < 10) ; // ERROR!

localToDoBlock 在循环外不可用,包括 while 条件本身。

但是,如果您在循环外声明计数器为

int outsideTheDoBlock = 1;
do {
       outsideTheDoBlock++;
} while (outsideTheDoBlock < 10) ; // Works now

编译器不再抱怨,因为 outsideTheDoBlock 在循环内外都可用。