So i'm doing a lab for my computer programming class on Arrays using Bubble Sort. Anyways the code is done and should work but one part is getting an error of 'Unreachable Code' and I have no idea why. I can't see the issue here. Here's the full code so you can identify the issue.
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();
}
}
The issue of the 'Unreachable code' occurs at line 29 and is the part that says "System.out.print("The new sequence is : \n ");" Please help if you can, thanks so much in advance :)
Try it like that:
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();
}
}
There are actually 3 problems. The first problem was the loop with condition 1>0. This one is always true. The other 2 problems were that you have loops with condition 1 < ar.length which is also infinite