Java数组排序:将排序逻辑封装为函数并调用的技术咨询
Fixing the Encapsulated Sorting Logic in Your Java Code
Hey there! I see you're trying to move your sorting logic into a separate method and ran into issues—let's get this sorted out (pun intended).
First, let's start with a complete, working version of your code with the sorting logic encapsulated properly:
import java.util.Arrays; public class Sort { public static void main(String args[]){ int [] array = new int[10]; // Populate the array with random numbers for ( int i = 0 ; i < array.length ; i++ ) { array[i] = ((int)(Math.random()*100+1)); } // Call our encapsulated sorting method sortArray(array); // Print the sorted array for ( int i = 0 ; i < array.length ; i++ ) { System.out.println(array[i]); } } // Encapsulated sorting method public static void sortArray(int[] inputArray) { // Arrays are passed by reference, so sorting this modifies the original array Arrays.sort(inputArray); } }
Let's break down the common pitfalls that might have tripped you up:
- Forgot the
java.util.Arraysimport: This is a super common mistake—Arrays.sort()lives in thejava.utilpackage, so you need that top-level import for the compiler to recognize the method. - Method accessibility mismatch: Since
main()is a static method, you either need to make your sorting method static too (like the example above) or create an instance of theSortclass to call a non-static method. For a simple utility like this, static is the most straightforward choice. - Array pass-by-reference confusion: In Java, arrays are passed by reference. That means when you sort
inputArrayinsidesortArray(), it directly modifies the originalarrayyou created inmain(). If you want to keep the original unsorted array intact, you can adjust the method to return a sorted copy instead:
public static int[] sortArray(int[] inputArray) { // Create a copy to avoid modifying the original array int[] sortedArray = Arrays.copyOf(inputArray, inputArray.length); Arrays.sort(sortedArray); return sortedArray; }
Then call it in main() like this:
int[] sortedArray = sortArray(array); // Print sortedArray instead of the original array
If you hit a specific compiler error or runtime exception, feel free to share the details and we can dig deeper—but this should cover the most common issues when encapsulating this logic.
内容的提问来源于stack exchange,提问作者E.A
相关产品推荐
相关产品推荐

