我正在尝试编写一些代码,根据用户输入的内容按升序或降序对数字进行排序。当用户输入“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] + " ");
}
}
}
最佳答案
看起来您调用了 in.nextLine()
两次。每次调用该函数时,程序都会从用户那里读取另一件事。
默认情况下,您的代码按升序运行。但是,由于您获得了两次输入,因此您需要输入“N”两次(当它“计数”时 - 即第二次,当您实际使用结果时)才能使其工作。
解决这个问题很简单:只需在声明 ascending
和 descending
之前删除 in.nextLine()
即可。
顺便说一句,您的用户输入测试代码比需要的要复杂一些。要正确设置升序
,您需要做的是:
ascending = in.nextLine().equalsIgnoreCase("y");
它使用 equalsIgnoreCase()
,这相当于获取第一个字符、将其大写并将其与 'Y'
进行比较的方法。
这将替换 for 循环之前的 if/elseif block 。
旁注 #2:for 循环中有很多重复的代码。由于唯一不同的是 if block 中的条件,因此您可以仅使用 boolean 表达式而不是内部 if/else 语句:
for (int i = 0; i < count; i++) {
for (int j = 0; j < count - 1; j++) {
boolean swap = ascending
? array[j] > array[j + 1]
: array[j] < array[j + 1];
if (swap) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
关于java - 需要输入两次 'N'才能显示相关信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27517092/