我是java的新手所以请在这个小问题上请我帮助我。
我想计算以下代码段中的第二大元素。 我怎样才能做到这一点?在此先感谢。
public class Marathan {
public static void main(String[] args) {``
String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil",
"Matt", "Alex", "Emma", "John", "James", "Jane", "Emily",
"Daniel", "Neda", "Aaron", "Kate" };
int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412,
393, 299, 343, 317, 265 };
for (int i = 0; i < times.length; i++) {
System.out.println(names[i] + "..." + times[i]);
}
double max=times[0];
double mix=times[0];
for(int x=0;x<times.length;x++){
if (times[x] > max) {
max = times[x];
}
if(times[x]<mix){
mix=times[x];
}
}
System.out.println("The Fastest Runner is " + max);
System.out.println("The Slowest Raccer is "+mix);
}}
答案 0 :(得分:0)
int max1,max2;
if(times[0]>times[1])
{
max1=times[0];
max2=times[1];
}
else
{
max1=times[1];
max2=times[0];
}
for(int i=2;i<times.length;i++)
if(times[x]>max1)
{
max2=max1;
max1=times[x];
}
else if(times[x]>max2)
max2=times[x];
答案 1 :(得分:0)
公共课Marathan { public static void main(String [] args){
String[] names = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil",
"Matt", "Alex", "Emma", "John", "James", "Jane", "Emily",
"Daniel", "Neda", "Aaron", "Kate"};
int[] times = {341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412,
393, 299, 343, 317, 265};
for (int i = 0; i < times.length; i++) {
System.out.println(names[i] + "..." + times[i]);
}
double max = times[0];
double mix = times[0];
for (int x = 0; x < times.length; x++) {
if (times[x] > max) {
max = times[x];
}
if (times[x] < mix) {
mix = times[x];
}
}
System.out.println("The Fastest Runner is " + max);
System.out.println("The Slowest Raccer is " + mix);
// If there are at least 2 values in times
int i1 = 0; // index of the largest
int i2 = 1; // index of the 2nd largest
if (times[i1] < times[i2]) {// then swap
int x = i1;
i1 = i2;
i2 = x;
}
for(int i = 2; i < times.length; ++i) {
if (times[i] > times[i1]) {
i2 = i1;
i1 = i;
} else if (times[i] > times[i2]) {
i2 = i;
}
}
System.out.println("The first is " + names[i1] + " with a time of " + times[i1]);
System.out.println("The second is " + names[i2] + " with a time of " + times[i2]);
}
}
答案 2 :(得分:0)
请确保您的代码看起来整齐,并有适当的缩进。我也不知道 double mix 在代码中起什么作用。现在问题,试试这个:
double max = times[0];
double secondHighest = times[0];
for(int x=0;x<times.length;x++){
if (times[x] > max) {
max = times[x];
secondHighest = highest;
}
else if ((times[x]>secondHighest) && (times[x] != max))
{
secondHighest = times[x];
}