0

Let me start by saying, this is NOT a homework question. I am not satisfied with the pace of my JAVA class, so I'm branching out and making personal programs that I would benefit from using. I copy and pasted a program to sort integers into descending order and modified it so it would sort doubles in ascending form to help with homework in my Stats class. (Yes, I know there are sorters on the web, just trying to develop my programming skills.) My question is how do I modify my program so that when the user has filled the array, the program automatically sorts the numbers without the user hitting "Enter" or using a loop to check for -1 or 0? This program satisfies my needs, but I'm thinking in terms of real world users. I tried searching for the answer, but maybe I'm not wording my question right. I hope I described my issue accurately, let me know if you have any suggestions, thank you.

Here's my code.

package sort_numbers_in_ascending_order;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("How Many Numbers Do You Want to Sort? ");
        int size  = input.nextInt();
        double[] newArr = new double [size];
        System.out.print("Enter " + size + " Numbers to Sort: ");

        for(int input_array = 0; input_array<size; input_array++) {
        //assigns values to array.
            newArr[input_array] = (double)input.nextDouble();
        }

        for(int enter_number = 0; enter_number < size; enter_number++) {
        //init. enter_number to 1,                                                                   
            // while enter_number is less than size
            for(int sort_num = 1; sort_num < size; sort_num++) {       
            // of array, processes through loops, increments
                //for loop sorts each index in array by processing 
                //each index through if loop.   
                if (newArr[sort_num] < newArr[sort_num-1]) { 
                //if an index is less than its neighbor on 
                    //r.h.s, swap values in indexes.
                    double swapNum = (double)newArr[sort_num];
                    newArr[sort_num] = newArr[sort_num-1];
                    newArr[sort_num-1] = swapNum;
                }
            }
        }
        System.out.println("Here are the Sorted Numbers: ");

        for (int printNum=0; printNum<size; printNum++) {
            System.out.print(newArr[printNum] + " ");//prints each index
        }
        System.out.println();
    }
}
4

1 回答 1

0

他们必须至少按一次回车键才能输入。

  1. 也许只是让他们输入要排序的数字,而不是最初说多少。这将要求您动态增长数字列表而不是固定大小的数组。

  2. 我知道你正在学习,但是像你一样对数组进行排序的性能很差,如果这不是为了家庭作业,最好的排序方法是使用Collections.sort()

于 2013-10-03T17:54:45.397 回答