我对编程和 Java 也是新手。我需要编写一个 void 方法来对输入的数组进行排序,我已经编写了代码,但不知道如何从 void 方法显示排序后的列表。任何愿意提供帮助的人。我们将不胜感激。
package util.assign4;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import util.IO;
public class UtilAssign4 {
public static int[] getData (String input){
StringTokenizer st = new StringTokenizer(input);
int []x = new int[st.countTokens()];
for(int i = 0;st.hasMoreTokens(); i++){
try{
x[i] = Integer.parseInt(st.nextToken());
}
catch(Exception e){
JOptionPane.showMessageDialog(null," Invalid input");
System.exit(1);
}
}
return x;
}
public static int getHighest(int g[]){
int hi = g[0];
for( int k = 1; k <g.length;k++)
if(g[k]> hi) hi = g[k];
return hi;
}
public static int getSmallest(int p[]){
int sm = p[0];
for(int l = 1;l<p.length;l++)
if(p[l] < sm) sm = p[l];
return sm;
}
public static float getAverage(int n[]){
float sum = 0.0f;
for(int y = 0;y <n.length; y++) sum += n[y];
return sum/n.length;
}
public static void getSorted(int grades []){
for(int i = 0; i<grades.length-1;i++){
int largest =i;
for(int j = 0;j<grades.length;j++)
if(grades[j]>grades[largest]) largest = j;
int temp = grades[largest];
grades[largest] = grades[i];
grades[i]=temp;
}
}
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enetr one or more grades:");
int [] x = getData(input);
int j = getHighest(x);
int m = getSmallest(x);
float a = getAverage(x);
IO.showMsg("Array you entered:" + input + String.format("\nThe"
+ " higheset grade is:%2d \n"
+ "The Lowest Grade is:%2d \n"+"The average is:%2.2f\n"
+ "The sorted list: ",
j,m,a));
}
}
最佳答案
您不应该在 sort
方法中打印数组的内容。您的要求(我打赌)是对提供给方法“就地”的数组进行排序(它看起来已经像您正在做的那样)。这意味着给定一个数组:
int[] grades = new int[] {34, 76, 12, 0, -1};
当你打电话时:
UtilAssign4.getSorted(grades);
传递到方法中的数组实际上是在方法内部排序的,因此不需要返回(这就是返回类型为 void 的原因)。总而言之,在调用排序方法之前,您的数组是未排序的。调用完成后,同一个数组现已排序。
现在您可以在调用方法中打印出排序后的数组(在本例中为 main(String[])
:
getSorted(x); // <-- call the sort function, on your array
String msg = String.format("\nThe higheset grade is:%2d \n"
+ "The Lowest Grade is:%2d \nThe average is:%2.2f\n"
+ "The sorted list: %s", j, m, a, Arrays.toString(x));
IO.showMsg(msg);
注意Arrays.toString(x)
吗?这将获取排序后的数组,并将其转换为字符串表示形式(看起来像这样:[76, 34, 12, 0, -1])。
关于java - 如何显示void方法的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802702/