如何仅使用if / else按升序排序5个数字来创建java程序。我不能用于进程或数组。 数字由用户输入 我的代码......
public static void main(String[] args) {
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;
int lugar1=0;
int lugar2=0;
int lugar3=0;
int lugar4=0;
int lugar5=0;
Scanner sc = new Scanner (System.in);
System.out.println("Enter first number");
a = sc.nextInt();
System.out.println("Enter second number");
b = sc.nextInt();
System.out.println("Enter third number");
c = sc.nextInt();
System.out.println("Enter fourth number");
d = sc.nextInt();
System.out.println("Enter fifth number");
e = sc.nextInt();
if(a>b&&a>c&&a>d&&a>e)
{
lugar1=a;
}
else {
if (b>c&&b>d&&b>e&&b>a)
{
lugar1=b;
}
else {
if (c>d&&c>e&&c>a&&c>b)
{
lugar1=c;
}
else {
if (d>e&&d>a&&d>b&&d>c)
{
lugar1=d;
}
else
{
lugar1=e;
}
}
}
}
if(a<b&&a<c&&a<d&&a<e)
{
lugar5=a;
}
else {
if (b<c&&b<d&&b<e&&b<a)
{
lugar5=b;
}
else {
if (c<d&&c<e&&c<a&&c<b)
{
lugar5=c;
}
else {
if (d<e&&d<a&&d<b&&d<c)
{
lugar5=d;
}
else
{
lugar5=e;
}
}
}
}
System.out.println(lugar1);
System.out.println(lugar5);
}
我不再那样走了,我只有1和5
答案 0 :(得分:2)
您的约束不会排除使用列表。见How to sort a ArrayList in Java?
如果您也不能使用列表,我建议您尝试使用Math.min,http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html,这样您就可以确定哪些是下一个最小值...
创建一个函数来打印下一个最小的。
private void printNextSmallest() {
int min = Math.min(Math.min(Math.min(a,b), Math.min(c,d)),e);
if (min == Integer.MAX) {return;}
else if (a == min) { System.out.println(a + " "); printNextSmallest(Integer.MAX, b, c, d,e);}
//..
else if (e == min) { System.out.println(e + " "); printNextSmallest(a, b, c, d, Integer.MAX);
}
答案 1 :(得分:1)
行。我点了一下子弹并输入了所有内容。没有循环,没有数组,没有任何东西。
基本思路是保持排序顺序。
import java.util.Scanner;
public class Sort5 {
static int a1 = Integer.MIN_VALUE, a2 = Integer.MIN_VALUE, a3 = Integer.MIN_VALUE, a4 = Integer.MIN_VALUE, a5 = Integer.MIN_VALUE;
public static void placeNext(int aNew) {
if (aNew > a5) {
a1 = a2;
a2 = a3;
a3 = a4;
a4 = a5;
a5 = aNew;
} else {
if (aNew > a4) {
a1 = a2;
a2 = a3;
a3 = a4;
a4 = aNew;
} else {
if (aNew > a3) {
a1 = a2;
a2 = a3;
a3 = aNew;
} else {
if (aNew > a2) {
a1 = a2;
a2 = aNew;
} else {
a1 = aNew;
}
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
placeNext(sc.nextInt());
placeNext(sc.nextInt());
placeNext(sc.nextInt());
placeNext(sc.nextInt());
placeNext(sc.nextInt());
System.out.println("" + a1 + " | " + a2 + " | " + a3 + " | " + a4 + " | " + a5);
}
}
除非我在某个地方输错,否则应适用于任何5 int
s。
答案 2 :(得分:0)
使用以下方法:
public int getSmallestInt(int... ints) {
int smallest = Integer.MAX_VALUE;
for (int i : ints) {
smallest = Math.min(smallest, i);
}
return smallest;
}
public int getLargestInt(int... ints) {
int largest = Integer.MAX_VALUE;
for (int i : ints) {
largest = Max.max(largest, i);
}
return largest;
}
或排序:
public static void main(String[] args) {
List<Integer> ints = new Test().sort(5, 1, 2);
System.out.println(ints.get(0)); //-> 1
}
public List<Integer> sort(Integer... ints) {
List<Integer> l = Arrays.asList(ints);
Collections.sort(l);
return l;
}