(这是一个项目,所以是的,这是家庭作业)
任务是使用用户输入创建数组(我能够做到),然后对于第二部分,使用单独的方法按升序对数组进行排序,然后将其输出。我已经让它做我需要的一切,除了我不知道如何让它排序。指示说使用从 0 到长度的 while 循环来找到最小值,然后将其与第一个交换,但我不知道该怎么做。这是我到目前为止所拥有的:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int storage = getNumDigits(in);
if(storage == 0){
System.out.print("No digits to store? OK, goodbye!");
System.exit(0);
}
int []a = new int [storage];
a = getDigits(a, in);
displayDigits(a);
selectionSort(a);
}
private static int getNumDigits(Scanner inScanner) {
System.out.print("Please enter the number of digits to be stored: ");
int stored = inScanner.nextInt();
while(stored < 0){
System.out.println("ERROR! You must enter a non-negative number of digits!");
System.out.println();
System.out.print("Please enter the number of digits to be stored: ");
stored = inScanner.nextInt();
}
return stored;
}
private static int[] getDigits(int[] digits, Scanner inScanner) {
int length = digits.length;
int count = 0;
int toBeStored = 0;
while(count < length){
System.out.print("Enter integer " +count +": ");
toBeStored = inScanner.nextInt();
digits[count] = toBeStored;
count++;
}
return digits;
}
private static void displayDigits(int[] digits) {
int len = digits.length;
System.out.println();
System.out.println("Array before sorting:");
System.out.println("Number of digits in array: " +len);
System.out.print("Digits in array: ");
for(int cnt = 0; cnt < len-1; cnt++){
System.out.print(digits[cnt] + ", ");
}
System.out.println(digits[len-1]);
}
private static void selectionSort(int[] digits) {
int l = digits.length;
System.out.println();
System.out.println("Array after sorting:");
System.out.println("Number of digits in array: " +l);
System.out.print("Digits in array: ");
int index = 0;
int value = digits[0];
int indVal = digits[index];
while(index < l){
indVal = digits[index];
if(indVal <= value){
indVal = value;
digits[index] = value;
index++;
}
else if(value < indVal){
index++;
}
System.out.print(value);
//This is where I don't know what to do.
}
}