有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

我对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) 个答案

  1. # 1 楼答案

    您的代码有一些问题。问题是

    1. 改变

       if(isEmpty());
      

       if(new Foo().isEmpty())
      

      由于isEmpty()是非静态的,因此无法从静态方法引用该方法并删除该额外分号

    2. 类未关闭(表示类末尾缺少}

    3. 你在哪里找到这个nextChar()方法的

      检查Scanner

      如果要从Scanner.next中获取第一个字符,则

      而不是

      kb.nextChar() == 'y'
      

      使用

      kb.next().charAt(0) == 'y'