初学者做while循环错误

时间:2015-02-19 02:39:26

标签: java loops while-loop

我无法弄清楚为什么我的代码的最后一行抛出错误“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);
}
}

2 个答案:

答案 0 :(得分:1)

cont在内部范围内声明,因此while循环无法使用。您需要在 do语句之前声明

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

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

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

答案 1 :(得分:1)

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

所以,在下面的代码中

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

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

但是,如果你将循环外的计数器声明为

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

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