【发布时间】:2015-02-15 11:59:37
【问题描述】:
我正在尝试编写一些代码,根据用户输入的内容按升序或降序对数字进行排序。当用户输入“Y”时,该程序能够按升序对它们进行排序,但是如果他们输入“N”以降序排序,则用户必须在显示之前将“N”输入两次。我已经发布了下面的语法,所以如果有人想告诉我缺少什么/做错了什么,请随时这样做。
import java.util.*;
public class SortProgram {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("\nHow many numbers do you want sorted?: ");
int count = in.nextInt();
int[] array = new int[count];
for (int i = 0; i < count; i++) {
System.out.print("Enter number #" + (i+1) + ": ");
array[i] = in.nextInt();
}
System.out.print("\nPress 'Y' to sort numbers in order, press 'N' to sort numbers in DESCENDING order: ");
in.nextLine();
boolean ascending = true;
boolean descending = false;
if (in.nextLine().toUpperCase().charAt(0) == 'Y') {
ascending = true;
} else if (in.nextLine().toUpperCase().charAt(0) == 'N') {
descending = true;
ascending = false;
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < count - 1; j++) {
if (ascending) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
} else if (!ascending) {
if (array[j] < array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
System.out.print("\nThe sorted numbers are: ");
for (int i = 0; i < count; i++) {
System.out.print(array[i] + " ");
}
}
}
【问题讨论】:
-
为什么
descending甚至是一个变量?你根本不用它。 -
一直在尝试解决各种问题,我想我会尝试一下。我对Java完全陌生,所以我不了解大众。你能看到很多错误吗?
-
你应该明确地将 in.nextline() 分配给一个变量,这样你就不会一直调用它,然后你可以检查变量的值。我不知道这是否会改变任何东西,因为我现在没有运行它,但这是一个很好的编码习惯
标签: java sorting compilation