簡體   English   中英

在Java中填充數組后如何停止接受用戶輸入

[英]How to Stop Accepting User Input Once Array is Filled in Java

讓我首先說,這不是一個作業問題。 我對JAVA上課的進度不滿意,因此我正在擴展並制作個人程序,我將從中受益。 我復制並粘貼了一個程序,以將整數按降序排序並對其進行了修改,因此它將以升序形式對雙精度進行排序,以幫助Stats類完成作業。 (是的,我知道網上有排序器,只是在嘗試提高我的編程技能。)我的問題是如何修改程序,以便當用戶填充數組時,程序自動對數字進行排序而不會導致用戶點擊“輸入”還是使用循環檢查-1或0? 該程序可以滿足我的需求,但是我在考慮實際用戶。 我嘗試搜索答案,但也許我的措詞不正確。 希望我能准確地描述我的問題,如果您有任何建議,請告訴我,謝謝。

這是我的代碼。

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();
    }
}

他們必須至少按一次Enter鍵才能輸入內容。

  1. 也許只是讓他們輸入要排序的數字,而不是最初說出多少。 這將要求您動態增長數字列表,而不是固定大小的數組。

  2. 我知道您正在學習,但是像對自己一樣對數組進行排序的性能很差,如果這不是用於家庭作業,則排序的最佳方法是使用Collections.sort()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM