我有两个数组列表,我在其中存储随机数..然后我计算第一个列表(player1)和第二个列表(player2)的最大数量...
我无法达到player1和player2的最大数量的问题,如您所见,代码将int max1 = Integer.MIN_VALUE;
与int max2 = Integer.MIN_VALUE;
进行比较code> .. 所以输出总是 tie
在我的代码中,我确实计算了player1和player2的最大数量,但我无法达到它们..
我怎样才能达到player1的最大数量并将其与player2的最大数量进行比较?
import java.util.ArrayList;
import java.util.Random;
public class Main {
int static maximum(ArrayList A){
int max=0;
for(int s=0; s<A.size(); s++){
if(A.get(s)>max){
max=A.get(s);
}
}
return max;
}
public static void main(String[] args) {
ArrayList<Integer> player1 = new ArrayList<Integer>();
ArrayList<Integer> player2 = new ArrayList<Integer>();
int max1=maximum(player1);
int max2=maximum(player2);
Random rn = new Random();
for (int i=0; i<=5; i++){
int value1 = rn.nextInt(13)+1;
player1.add(value1);
}
System.out.println(player1);
for (int i=0; i<=5; i++){
int value2 = rn.nextInt(13)+1;
player2.add(value2);
}
System.out.println(player2);
if(max1>max2){
System.out.println("player1 is winner");
} else if (max1<max2){
System.out.println("player2 is winner");
} else {
System.out.println("tie");
}
}
}
最佳答案
也许你应该检查这里的玩家二,而不是玩家一。 这是您所做的:
int max2 = Integer.MIN_VALUE;
for(int s=0; s<player1.size(); s++){
if(player1.get(s)>max2){
max2=player1.get(s);
}
}
正确的应该是:
int max2 = Integer.MIN_VALUE;
for(int s=0; s<player2.size(); s++){
if(player2.get(s)>max2){
max2=player2.get(s);
}
}
EDIT:
您可以直接从 main() 调用:
max1 = maximum(player1);
max2 = maximum(player2);
int maximum(ArrayList A)
{
int max = 0;
for(int s=0; s<A.size(); s++){
if(A.get(s)>max){
max=A.get(s);
}
}
return max;
}
然后按照您所做的那样比较 max1 和 max2。
EDIT 2 :
import java.util.ArrayList;
import java.util.Random;
public class Main {
int static maximum(ArrayList A){
int max=0;
for(int s=0; s<A.size(); s++){
if(A.get(s)>max){
max=A.get(s);
}
}
return max;
}
public static void main(String[] args) {
ArrayList<Integer> player1 = new ArrayList<Integer>();
ArrayList<Integer> player2 = new ArrayList<Integer>();
Random rn = new Random();
for (int i=0; i<=5; i++){
int value1 = rn.nextInt(13)+1;
player1.add(value1);
}
System.out.println(player1);
for (int i=0; i<=5; i++){
int value2 = rn.nextInt(13)+1;
player2.add(value2);
}
System.out.println(player2);
int max1=maximum(player1);
int max2=maximum(player2);
if(max1>max2){
System.out.println("player1 is winner");
} else if (max1<max2){
System.out.println("player2 is winner");
} else {
System.out.println("tie");
}
}
}
关于java - 如何从两个列表中达到最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32659442/