-4

我有两个嵌套开关,我想在另一个开关案例中使用一个开关案例的值。如下例所示,我想使用双变量temp_usr并将其作为参数传递给另一个 switch 案例中的方法(cels()),我该怎么做?

switch( switch1){
case 1: 
{
System.out.println(" You have selected Celsius");
Scanner temp_ip= new Scanner(System.in);
System.out.println("Please enter the temperature in celsius");
double temp_usr= temp_ip.nextDouble();
}   
break;
case 2: ...............
case 3: ...............

switch(switch2) {
case 1: 
{
System.out.println("convert it into Celsius");
System.out.println(cels(arg));  /*this argument should take value of temp_usr*/
}
break;
case 2: .........  
case 3: ......... 
4

2 回答 2

1

该变量在它定义的块内可见。如果要打开可见性,请在开关外声明。试试这个:

double temp_usr= 0.0; //declaring here switch will make it visible in the following code
switch( switch1){
case 1: 
{
System.out.println(" You have selected Celsius");
Scanner temp_ip= new Scanner(System.in);
System.out.println("Please enter the temperature in celsius");
temp_usr= temp_ip.nextDouble();
}   
break;
case 2: ...............
case 3: ...............

switch(switch2) {
case 1: 
{
System.out.println("convert it into Celsius");
System.out.println(cels(arg));  /*this argument should take value of temp_usr*/
}
break;
case 2: .........  
case 3: ......... 
于 2013-08-24T08:14:34.033 回答
0

首先,那些不是嵌套开关。

确保默认情况下也会产生可访问的temp_usr. 首先,出于范围原因,我将在 switch 语句之外声明它:

double temp_usr=0;

我会在每个 case 块中设置它,并允许default保留0.

然后,对于第二个 switch 语句,它将是可用的、有效的并且在没有编译器错误的范围内。

于 2013-08-24T08:12:35.277 回答