gpt4 book ai didi

java - 已声明时找不到符号

转载 作者:行者123 更新时间:2023-12-02 02:26:23 24 4
gpt4 key购买 nike

请有人帮助我解决此错误:

import java.util.*;
class Cinema
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
int t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
int t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
int t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}

我已经在 case block 中声明了变量 t 但它找不到它。我查看了许多类似问题的答案,但似乎无法解决

最佳答案

您需要在 switch block 之前声明变量,以便可以在 switch block 之外访问它......请参阅下面的内容

import java.util.*;
public class Cinema {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();

int t = 0;
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}

关于java - 已声明时找不到符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717460/

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