我在以下代码段中遇到有关变量范围的问题。有人可以快速概述一下为什么 java 在打印时“找不到输出符号”吗?谢谢。
class Main
{
public static void main(String[] args) {
String text = "hello";
if (text.indexOf(" ") == -1) //if a space doesn't exist
{
String output = "one word";
}
else
{
String output = "more than one word";
}
System.out.println(output);
}
}
最佳答案
变量output
仅存在于包含代码块中,该代码块当前似乎位于if
block 和else<中
block ,如果要访问 if
和 else
block 之外的变量 output
,则需要在之前定义它if
block 。
关于Java 输出变量作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43712053/