以下是我的Java编程课程中的一项作业。我已经编写了所有代码,只是无法确定如何使输出显示我需要显示的内容。
对于我的作业,我必须编写一个具有一维数组的程序,该数组容纳10个介于1和100之间的整数,并使用冒泡排序对数组进行排序。
输出看起来像一个例子:
未排序的列表是: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] + ", ");
}
}
}
最佳答案
改变这个循环
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] + ", ");
}
}
关于java - 在最后一个元素之前用“和”打印int数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40641394/