我对我的程序遇到的问题是当我打印所有号码时,我输入的第一个号码重复两次并替换第二个号码
实施例。如果我输入1,3,5,7,9,11,13,15,17,19输出为1,1,5,7,9,11,13,15,17,19
我该如何解决这个问题?
import java.util.Scanner;
import java.util.Arrays;
public class InputSort_Integers
{
public static void main(String[] args)
{
// Declarations
final int[] count = new int [10];
// Scanner
Scanner scanner = new Scanner(System.in);
// Scanner Loop
for (int i = 0; i < count.length; i++)
{
System.out.print("Enter " + count.length + " numbers (Press enter after each entry): ");
count[i] = scanner.nextInt();
}
// Print sorted number
int sorted = printNumbers(count);
}
public static int printNumbers(int[] count)
{
// Print loop
for (int i=0; i<count.length; i++)
{
System.out.println(count[i]);
// Sort Numbers
Arrays.sort(count);
}
return count.length;
}
}
答案 0 :(得分:1)
您正在打印第一个数字,然后从循环内进行排序。在循环开始之前,您应该对数字进行一次排序。将您的printNumbers
方法更改为:
public static int printNumbers(int[] count)
{
// Sort Numbers
Arrays.sort(count);
// Print loop
for (int i=0; i<count.length; i++)
{
System.out.println(count[i]);
}
return count.length;
}
答案 1 :(得分:0)
你只调用一次Arrays.sort,而不是每次调用你的循环。更正了printNumbers:
public static int printNumbers(int[] count)
{
// Sort Numbers
Arrays.sort(count);
// Print loop
for (int i = 0; i < count.length; ++i)
{
System.out.println(count[i]);
}
return count.length;
}
答案 2 :(得分:0)
当你想要在for循环之前调用它时,你正在for循环中调用Arrays.sort(count);
。当我删除这一行时,它修复了问题。