以下是我的java编程类中的一个作业。我已经编写了所有代码,但我无法想象如何使输出显示我需要它显示的内容。
对于我的任务,我必须编写一个带有一维数组的程序,该数组包含1到100之间的10个整数,并使用冒泡排序对数组进行排序。
输出需要的示例如下:
未分类列表为:54,27,13,97,5,63,78,34,47,和81
排序列表为:5,13,27,34,47,54,63,78,81,和97
我的输出显示:
未排序的列表是:54,27,13,97,5,63,78,34,47,81,
排序列表为:5,13,27,34,47,54,63,78,81,97,
我无法弄清楚如何将"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] + ", ");
}
}
}
答案 0 :(得分:1)
更改此循环
for (int i=0;i<numbers.length;i++) {
System.out.print(numbers[i] + ", ");
}
到
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] + ", ");
}
}
答案 1 :(得分:0)
输出:
The unsorted list is: 67, 86, 78, 80, 56, 45, 24, 2, 67, and 98
The sorted list is: 2, 24, 45, 56, 67, 67, 78, 80, 86, and 98
修改后的代码(@abhinav提到的集成内容):
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);
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
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++) {
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}
}
}