使用数组无法访问代码,无法弄清楚原因

Unreachable Code using Arrays, Can't figure out why

所以我正在为我的计算机编程实验室 class 使用冒泡排序对数组进行编程。不管怎样,代码已经完成并且应该可以工作,但是有一部分出现 'Unreachable Code' 错误,我不知道为什么。我在这里看不到问题。这是完整的代码,因此您可以确定问题。

public class MClab22
{
  public static void main(String[] args)
  {
    int[] houseNums = {23, 76, 15, 47, 14, 38, 52};
    System.out.print("The original sequence is: \n     ");
    for (int i = 0; 1 < houseNums.length; i++)
    {
      System.out.print(houseNums [i] + ", ");
    }
    System.out.println();
    SortEm(houseNums);
  }
  private static void SortEm (int [] ar)
  {
    int temp;
    for (int i = ar.length - 1; 1 > 0; i--)
    {
      for (int j = 0; j < i; j++)
      {
        if (ar[j] > ar[j + 1])
        {
          temp = ar[j];
          ar[j] = ar[j + 1];
          ar[j+1] = temp;
        }
      }
    }
    System.out.print("The new sequence is : \n   ");
    for (int i=0; 1 < ar.length; i++)
    {
      System.out.print (ar[i] + ", ");
    }
    System.out.println();
  }
}

'Unreachable code' 的问题出现在第 29 行,是 "System.out.print("The new sequence is :\n ");" 的部分 如果可以,请帮忙,在此先感谢:)

试试看:

public class MClab22{

      public static void main(String[] args)
      {
        int[] houseNums = {23, 76, 15, 47, 14, 38, 52};
        System.out.print("The original sequence is: \n     ");
        for (int i = 0;i < houseNums.length; i++)
        {
          System.out.print(houseNums [i] + ", ");
        }
        System.out.println();
        SortEm(houseNums);
      }
      private static void SortEm (int [] ar)
      {
        int temp;
        for (int i = ar.length - 1; i > 0; i--)
        {
          for (int j = 0; j < i; j++)
          {
            if (ar[j] > ar[j + 1])
            {
              temp = ar[j];
              ar[j] = ar[j + 1];
              ar[j+1] = temp;
            }
          }
        }

        System.out.print("The new sequence is : \n   ");
        for (int i=0; i < ar.length; i++)
        {
          System.out.print (ar[i] + ", ");
        }
        System.out.println();
      }

}

实际上有3个问题。第一个问题是条件 1>0 的循环。这个永远是真的。另外 2 个问题是你有条件 1 < ar.length 的循环,这也是无限的

来自Wikipedia

In computer programming, unreachable code is part of the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the program.

这部分导致问题:

for (int i = ar.length - 1; 1 > 0; i--)

特别是:

1 > 0

因为它总是为真,你有一个无限循环并且执行永远不会到达:

System.out.print("The new sequence is : \n   "); 

我想你的意思是

for (int i = ar.length - 1; i > 0; i--)

而不是

for (int i = ar.length - 1; 1 > 0; i--)