-4

2 つのネストされたスイッチがあり、1 つのスイッチ ケースの値を別のスイッチ ケースで使用したいと考えていました。以下の例のように、double 変数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;

各ケースブロックに設定し、default保持できるようにし0ます。

次に、2 番目の switch ステートメントのコンパイル エラーなしで、有効で有効になり、有効になります。

于 2013-08-24T08:12:35.277 に答える