我使用数组和方法编写了一个代码,该代码允许用户输入任意数量的数字,并且 显示从最小到最大的数字,但是该程序可以运行,但是没有显示数字,这是我写的代码
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers you want to enter? ");
int size = s.nextInt();
int i;
double[] numbers1 = new double[size];
System.out.println("Enter " + numbers1.length + " numbers: ");
getNumbers(numbers1);
double[] numbers2 = new double[numbers1.length];
for (i = 0; i < numbers1.length; i++) {
numbers2[i] = numbers1[i];
}
displayNumbers(numbers1);
System.out.println("The numbers after sorting are: ");
sortNumbers(numbers2);
displayNumbers(numbers2);
}
public static void getNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
}
}
public static void sortNumbers(double[] numbers) {
double temp;
double pass;
for (pass = 0; pass < numbers.length; pass++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
public static void displayNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
System.out.print(numbers + " ");
}
System.out.println();
}
}
答案 0 :(得分:1)
您的displayNumbers()
方法错误。在循环中,您写道:
numbers[i] = s.nextDouble();
System.out.print(numbers + " " );
您正试图再次读取4个double(每次调用该方法),并且正在打印整个数组(它并没有达到您的期望)。您可能想要的是这样:
System.out.print(numbers[i] + " " );
答案 1 :(得分:0)
您的代码效率低下,不清楚。
您不需要每次都创建一个新的Scanner
,也不需要为什么用println
代替Arrays.toString(double[])
这个数组。
您还应该提供更简洁的说明和变量名。
下面是代码的示例
public static void main(String[] args)
{
//create a new Scanner with a name that defines it
Scanner scanner = new Scanner(System.in);
//print your instructions
System.out.println("How many numbers would you like to sort?");
//print "> " to let the user to know he should be entering values
System.out.print("> ");
//read the number the user has entered which we will define as how many numbers he would enter next
int totalNumbers = scanner.nextInt();
//create a new array the size of the total numbers
double[] unsortedNumbers = new double[totalNumbers];
//tell the user to enter his unsorted numbers
System.out.println("Enter your unsorted numbers: ");
//loop totalNumbers times until the whole unsortedNumbers is full
for(int index = 0; index < totalNumbers; index++)
{
System.out.print("> ");
unsortedNumbers[index] = scanner.nextDouble();
}
//Print the numbers he entered
System.out.println("You entered: ");
//Arrays.toString prints the array in format [number, number, ...]
System.out.println(Arrays.toString(unsortedNumbers));
//sort the arrays with Arrays.sort which sorts in ascending numerical order
Arrays.sort(unsortedNumbers);
//Print the final result - sorted numbers
System.out.println("Sorted: " + Arrays.toString(unsortedNumbers));
}