John - 1 year ago 87

Java Question

The following is for one of my assignments in my java programming class. I have all the code written already I just can't figure how to make the output display what i need it to display.

For my assignment I have to write a program with a single-dimension array that holds 10 integer numbers between 1 and 100 and sort the array using a bubble sort.

An example of what the output needs to look like is this:

The unsorted list is: 54, 27, 13, 97, 5, 63, 78, 34, 47, **and 81**

The sorted list is: 5, 13, 27, 34, 47, 54, 63, 78, 81, **and 97**

My output is displaying this:

The unsorted list is: 54, 27, 13, 97, 5, 63, 78, 34, 47, 81,

The sorted list is: 5, 13, 27, 34, 47, 54, 63, 78, 81, 97,

I can't figure out how to write the

`"and"`

`public class Chpt7_Project {`

/** The method for sorting the numbers */

public static void bubbleSort(int[] numbers)

{

int temp;

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

{

for (int j = 0; j < i; j++)

{

if (numbers[j] > numbers[j + 1])

{

temp = numbers[j]; // swap number[i] with number[j]

numbers[j] = numbers[j + 1];

numbers[j + 1] = temp;

}

}

}

}

public static void main(String[] args) { // Test Method

System.out.print("The unsorted list is: ");

// Generate 10 random numbers between 1 and 100

int[] numbers = new int[10];

for (int i=0;i<numbers.length;i++) {

numbers[i] = (int) (Math.random() * 100);

System.out.print(numbers[i] + ", ");

}

System.out.println();

bubbleSort (numbers); // numbers are sorted from smallest to largest

System.out.print("The sorted list is: ");

for (int i=0;i<numbers.length;i++) {

System.out.print(numbers[i] + ", ");

}

}

}

Answer Source

Change this loop

```
for (int i=0;i<numbers.length;i++) {
System.out.print(numbers[i] + ", ");
}
```

to

```
for (int i=0;i<numbers.length;i++) {
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}
```