首先,是的,我正在编写编程任务的简介,但是我花了一整天的时间试图解决此问题,但取得了一些进展,但没有成功。
练习是要创建一种将3个int从最小到最大排序的方法。不鼓励我们使用数组,但是在这一点上,我无法弄清楚在没有数组帮助的情况下如何实现这一点。
我从简单地尝试弄清楚如何对3个整数进行“排序”开始,这就是我想到的:
public class SortInteger {
public static void main(String[]args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
int n1, n2, n3 = 0;
if (a < b && a < c) { n1 = a; }
else if (b < a && b < c) { n1 = b; }
else { n1 = c; }
if (a > b && a > c) { n3 = a; }
else if (b > a && b > c) { n3 = b; }
else { n3 = c; }
if (n1 < a && a < n3) { n2 = a; }
else if (n1 < b && b < n3) { n2 = b; }
else {n2 = c;}
System.out.println( n1 + " " + n2 + " " + n3);
}
}
我觉得我可以轻松地减少if语句的数量并简化上述代码中的许多行,但是我想等到成功后再开始清理程序。同样,该代码可以工作,但目标是将其编写为静态方法。因此,在走了这么远之后,我开始尝试将其转换为静态方法,并且走了这么远:
public class SortInteger2 {
public static int sort(int a, int b, int c) {
int []s = new int [3];
if (a < b && a < c) { s[0] = a; }
else if (b < a && b < c) { s[0] = b; }
else {s[0] = c;}
if (a > b && a > c) { s[2] = a; }
else if (b > a && b > c) { s[2] = b; }
else {s[2] = c;}
if (s[0] < a && a < s[2]) { s[1] = a; }
else if (s[0] < b && b < s[2]) { s[1] = b; }
else {s[1] = c;}
return s[]; //I dont know how to return an array, this didnt work for me
}
public static void main(String[]args) {
int A = Integer.parseInt(args[0]);
int B = Integer.parseInt(args[1]);
int C = Integer.parseInt(args[2]);
int []S = new int [3];
S = sort(A,B,C);
System.out.println(S[0] + " " + S[1] + " " + S[2]);
}
}
我知道我只能返回单个对象,这就是为什么我选择使用数组存储三个整数,然后简单地返回单个对象即数组的原因。但是,当我尝试时,编译器仍然对我大喊大叫。我在这里想念什么?我觉得它是如此明显,但是当我一遍又一遍地检查它时,并没有什么东西点击。如果我能朝着正确的方向前进,我将不胜感激!
“我认为我可以轻松地减少if语句的数量并简化上述代码中的许多行,”
您可以继续使用a,b,c而不是创建新变量,并根据它们的比较来交换它们,但是除此之外,没有什么可以减少的了。
“此外,该代码有效,但目标是将其编写为静态方法。”
为什么不这样做呢?
public static void sort(int a, int b, int c) {
...
System.out.println( n1 + " " + n2 + " " + n3);
}
public static void main(String[] args) {
sort(2, 5, 9);
}
如果您仍然打算使用数组,请将的返回值更改sort
为int[]
。然后,将行更改return s[]
为return s
,表示您要返回数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句