[英]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键才能输入内容。
也许只是让他们输入要排序的数字,而不是最初说出多少。 这将要求您动态增长数字列表,而不是固定大小的数组。
我知道您正在学习,但是像对自己一样对数组进行排序的性能很差,如果这不是用于家庭作业,则排序的最佳方法是使用Collections.sort()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.