使用变量,在 switch 语句中初始化,在外部
我在访问 switch 语句中初始化的变量,然后在 switch 外部使用它们时遇到问题。
这就是我的代码应该产生的结果: 什么是:X(+-* 或 /)X
这是我的 Java 代码:
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[]args){
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int svar, ans;
int tal1 = rand.nextInt(100) + 1;
int tal2 = rand.nextInt(100) + 1;
String characters = "+-*/";
int r = rand.nextInt(characters.length());
char randomChar = characters.charAt(r);
switch(randomChar){
case '+':
ans = tal1 + tal2;
break;
case '-':
ans = tal1 - tal2;
break;
case '*':
ans = tal1 * tal2;
break;
case '/':
ans = tal1 / tal2;
break;
}
System.out.println("What is: "+tal1+randomChar+tal2+"?");
svar = sc.nextInt();
if (svar == ans)
System.out.println("Correct!");
else
System.out.println("Wrong - Right answer: "+ans);
}
}
如您所见,“ans”已被声明并初始化。但是,我想在 if 语句(为了比较结果)和输出中使用 ans 变量。
现在我可以扩展每个案例并编写 if 语句和输出,但是代码会太多,因为我正在尝试执行类似的代码,但更小。这项工作如何运作有什么建议吗?
这是我得到的编译错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable ans may not have been initialized
The local variable ans may not have been initialized
at Test2.main(Test2.java:36)
I have an issue with accessing variables initialized in a switch-statement, and then using them outside switch.
This is what my code should produce:
What is: X (+-* or /) X
Here's my Java code:
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[]args){
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int svar, ans;
int tal1 = rand.nextInt(100) + 1;
int tal2 = rand.nextInt(100) + 1;
String characters = "+-*/";
int r = rand.nextInt(characters.length());
char randomChar = characters.charAt(r);
switch(randomChar){
case '+':
ans = tal1 + tal2;
break;
case '-':
ans = tal1 - tal2;
break;
case '*':
ans = tal1 * tal2;
break;
case '/':
ans = tal1 / tal2;
break;
}
System.out.println("What is: "+tal1+randomChar+tal2+"?");
svar = sc.nextInt();
if (svar == ans)
System.out.println("Correct!");
else
System.out.println("Wrong - Right answer: "+ans);
}
}
As you can see, "ans" has been declared and initialized. However, I want to utilize the ans variable in both the if statement (in order to compare the result) and the output.
Now I could expand each case and write both the if statements and the outputs, but the code would be too exessive as I'm trying to do a similar code, but smaller. Any tips how this work would work?
Here's the compilation error I get:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable ans may not have been initialized
The local variable ans may not have been initialized
at Test2.main(Test2.java:36)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
添加
default
大小写以捕获任何无法识别的输入。在您的情况下,这可能会引发RuntimeException
,因为如果达到这种情况,您的代码就会出现问题。您收到的错误意味着存在无法初始化
ans
的代码路径。 不要采取简单的方法,在声明时使用无意义的值初始化ans
!这只会隐藏有关代码实际问题的宝贵警告。Add a
default
case to catch any input that isn't recognized. In your case, this could throw aRuntimeException
, since something is wrong with your code if this case is reached.The error you are getting means that there is a code path that fails to initialize
ans
. Do not take the easy way out and initializeans
with a meaningless value when it is declared! That will just hide this valuable warning about a real problem with your code.与实例变量不同,局部变量不会自动初始化。
您需要显式地将其初始化为默认值。
如果您的
switch
中所有情况都失败,则ans
将永远不会被初始化。Unlike instance variables, local variables are not automatically initialized.
You need to explicitly initialize it the default value.
If all the cases fail in your
switch
thenans
will never be initialized.诸如
ans
之类的局部变量必须在使用前进行初始化。因此只需将 0 分配给
ans
Local variables such as
ans
must be initialized prior to usage.So just assign zero to
ans
如果你声明一个局部变量(在函数内部),你应该总是初始化它,
如果你在函数外部声明它,那么它将自动初始化为 0,但这对于这个来说不是一个好的做法
If you declare a local var (inside a function) you should always initialize it
if you declare it outside of a function then it will be automatically initialized with 0, but that's not good practice for this one
你会得到这个编译错误,因为编译器不知道 ans 是否会被初始化,
原因是在编译时不知道是否会执行 switch 条件,因此会出现编译错误。要解决此问题,请将 ans 初始化为某个值,例如:
另请参阅此帖子 和 这个
You get this compilation error because compiler doesnt know if ans will ever be initialized,
reason being at the compile time it is not known if the switch condition will ever be executed hence the compilation error. To resolve it initialize ans to some value like :
Also take a look at this post and this
只需将声明
int svar, ans;
更改为int svar, ans=0;
即可消除此错误。问题是你的变量 ans 没有在这一行初始化:if (svar == ans)
并且你的 switch case 没有default
case。Just change your declaration
int svar, ans;
toint svar, ans=0;
to remove this error. Problem is that your variable ans is not initialized at this line:if (svar == ans)
and your switch case doesn't havedefault
case.您在切换之前没有初始化 ans。
我不推荐埃里克森的答案,因为你的 randomChar 只会给你处理过的输入(你永远不会达到默认情况)。
You did not initialize ans before the switch.
I don't recommend erikson's answer, as your randomChar will only give you handled inputs (you'll never reach default case).