[英]Getting the second highest and second lowest java
在不使用数组数组排序或任何排序方法的情况下获取第二高和第二低的Java,仅用于循环的min_value和max_value,如果语句我已经开始进行编码,这是我到目前为止完成的所有操作,我想不到如何才能获得第二低的Java第二高
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);
}
}
只要改善您的状况以涵盖所有情况,
// 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.
显然,对数组进行排序是显而易见的解决方案,因此我认为这是某种测试分配。 无论如何,我猜最简单的方法就是让变量具有最高和第二高的值(最低也要相同)。 例如,要找到第二高的位置:
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);
您还需要相应地更新变量的值:
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) {
sh = fh; // We have got new fh so sh is old value of fh.
fh = n;
}
if (fl > n) {
sl = fl;
fl = n;
}
}
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);
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.