获得第二高和第二低的java而不使用数组数组排序或任何排序方法,min_value和max_value仅用于循环和if语句我已经开始编码这是我到目前为止所做的我无法想到我怎么能得到第二低和第二高
package Lab2;
import java.util.Scanner;
public class hehe {
public static void main(String[] args) {
int fh, sh, fl, sl, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter 5 numbers: ");
x = fh = sh = sl = fl = s.nextInt();
int a,b,c,d;
int mid = 0;
for (int i = 0; i < 4; ++i) {
int n = s.nextInt();
if (fh < n) {
fh = n;
}
if (fl > n) {
fl = n;
}
for(int y=0;y<5;y++){
}
}
System.out.println("The First highest is: " + fh);
System.out.println("The Second highest is: " + sh);
System.out.println("The Second lowest is: " + sl);
System.out.println("The First lowest is: " + fl);
System.out.println(mid);
}
}
答案 0 :(得分:2)
只是改善你的条件以涵盖所有情况,
// Initialize your variables like this,
fh = sh = Integer.MIN_VALUE;
fl = sl = Integer.MAX_VALUE;
// Change your for loop condition to below and get input only inside the loop. Not before it.
for (int i = 0; i < 5; ++i) {
if (fh < n) { // It means you have received the highest known number
sh = fh; // The existing highest becomes the second highest now
fh = n; // n should now be the (first) highest rightfully
} else if (sh < n) { // This means n was not the highest, but second highest
sh = n;
}
// Do the same for lowest also.
答案 1 :(得分:1)
显然,对数组进行排序是显而易见的解决方案,因此我认为这是某种测试任务。无论如何,我想最简单的方法就是将变量分别设置为最高和第二高(同样为最低)。例如,找到第二高:
List<Integer> values = new ArrayList<>();
for(int i = 0; i < 20; i++) {
values.add((int) (Math.random() * 10));
}
int highest = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for(int n: values) {
if(n > highest) {
second = highest;
highest = n;
} else if(n > second) {
second = n;
}
}
System.out.println("2nd highest: " + second);
答案 2 :(得分:0)
if (fh < n) {
sh = fh;
fh = n;
}else if (sh < n)
{
sh = n;
}
if (fl > n) {
s1=f1
fl = n;
}else if (s1 > n)
{
s1 = n;
}