我对eclipse上的以下Java代码有一个问题(无法访问的代码)
首先,我想澄清这一点。以下是大学的家庭作业,因此,由于大学关于剽窃的规定,我无法发布实际代码。但这里有一个修改过的代码,可以解释我的问题
守则:
import java.util.*;
public class Foo
{
//creating an object array
private static Object[] objectArray;
//main method
public static void main(String []args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Would you like to initialize array (y/n)?");
if(kb.nextChar() == 'y')
{
initializeArray();
}
someMethod();
}
public static void someMethod()
{
//checking if the array is empty, if the case, quit the method
if(isEmpty());
{
System.out.println("Empty array");
return;
}
//if the above check returns false (array is not empty) continues on
//with the code which is tagged by eclipse as unreachable
}
public static boolean isEmpty()
{
for(Object a : objectArray)
{
if(a != null)
{
return false;
}
}
return true;
}
public static void initializeArray()
{
objectArray[0] = new Object();
}
}
现在回答我的问题:
上面的代码给出了一个由于unreachable code
引起的错误。我反复检查,我知道获取unreachable code
的唯一方法是如果isEmpty
总是返回false
。事实并非如此。这可能是eclipse中的错误吗?如果这是我的错误,请你详细解释一下我哪里出了错
# 1 楼答案
您的代码有一些问题。问题是
改变
到
由于
isEmpty()
是非静态的,因此无法从静态方法引用该方法并删除该额外分号类未关闭(表示类末尾缺少
}
)你在哪里找到这个
nextChar()
方法的检查Scanner类
如果要从
Scanner.next
中获取第一个字符,则而不是
使用