简体   繁体   English

if-else if语句中如何进行两个运算?

[英]How can two operations be in if-else if statement?

I am trying to do make a simple soccer simulation program but I have an issue on matching teams to each other. 我正在尝试制作一个简单的足球模拟程序,但是在团队之间进行配对时遇到了问题。 if statement quits the loop after finding one condition. 如果找到一个条件,则if语句退出循环。 But I want to do two condition and two operations. 但是我想做两个条件和两个操作。 Is it possible? 可能吗?

package soccer.simulator;
import java.util.Random;
/**
 * @author Sertac
 */
public class SoccerSimulator {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int HomeTeamScore = 0;
        int AwayTeamScore = 0;
        Random randomGenerator = new Random();

        String HomeTeam = new String();
        String AwayTeam = new String();
        int HomeTeamID = randomGenerator.nextInt(10);
        int AwayTeamID = randomGenerator.nextInt(10);

        if(HomeTeamID == AwayTeamID){
            while (HomeTeamID != AwayTeamID){
                AwayTeamID = randomGenerator.nextInt(10);
            }
        }

        if(HomeTeamID == 0 || AwayTeamID == 0){
            if(HomeTeamID == 0){
                HomeTeam = "Arsenal";
            }else{
                AwayTeam = "Arsenal";
            }
        } else if(HomeTeamID == 1 || AwayTeamID == 1){
            if(HomeTeamID == 1){
                HomeTeam = "Barcelona";
            }else{
                AwayTeam = "Barcelona";
            }
        } else if(HomeTeamID == 2 || AwayTeamID == 2){
            if(HomeTeamID == 2){
                HomeTeam = "Bayern Munich";
            }else{
                AwayTeam = "Bayern Munich";
            }
        } else if(HomeTeamID == 3 || AwayTeamID == 3){
            if(HomeTeamID == 3){
                HomeTeam = "Chelsea";
            }else{
                AwayTeam = "Chelsea";
            }
        } else if(HomeTeamID == 4 || AwayTeamID == 4){
            if(HomeTeamID == 4){
                HomeTeam = "Borussia Dortmund";
            }else{
                AwayTeam = "Borussia Dortmund";
            }
        } else if(HomeTeamID == 5 || AwayTeamID == 5){
            if(HomeTeamID == 5){
                HomeTeam = "Galatasaray";
            }else{
                AwayTeam = "Galatasaray";
            }
        } else if(HomeTeamID == 6 || AwayTeamID == 6){
            if(HomeTeamID == 6){
                HomeTeam = "Juventus";
            }else{
                AwayTeam = "Juventus";
            }
        } else if(HomeTeamID == 7 || AwayTeamID == 7){
            if(HomeTeamID == 7){
                HomeTeam = "Manchester United";
            }else{
                AwayTeam = "Manchester United";
            }
        } else if(HomeTeamID == 8 || AwayTeamID == 8){
            if(HomeTeamID == 8){
                HomeTeam = "Milan";
            }else{
                AwayTeam = "Milan";
            }
        } else if(HomeTeamID == 9 || AwayTeamID == 9){
            if(HomeTeamID == 9){
                HomeTeam = "Real Madrid";
            }else{
                AwayTeam = "Real Madrid";
            }
        }

        //Generating each random integers in range 0..99 for 90 minutes
        for(int minutes = 0; minutes <= 90; minutes++){
            int randomInt = randomGenerator.nextInt(100);

            //if random int equals 0,1,2 home team scores
            if(randomInt < 3){ HomeTeamScore = HomeTeamScore + 1; }

            //if random int equals 98,99 away team scores
            //home team has 1 more int because playing at home is better
            if(randomInt > 97){ AwayTeamScore = AwayTeamScore + 1; }                         
        }
        System.out.println ("Simulation for match of the week:");
        System.out.println (HomeTeam + " " + HomeTeamScore + " - " + AwayTeamScore + " " + AwayTeam);

        }   
    }

And the output is: 3 - 1 Arsenal 输出为: 3 - 1 Arsenal

or: Arsenal 2 - 1 或: Arsenal 2 - 1

You only set one team name because there's no loop at all, only one final condition will be true in your huge if-else statement. 您只设置一个团队名称是因为根本没有循环,在您庞大的if-else语句中只有一个最终条件是正确的。 An easier approach (and highly recommendable in order to keep the sanity for anyone else that will touch your code in the near future) would be storing your team names in an array.- 一种更简单的方法(强烈建议使用此方法,以使在不久的将来会碰到您代码的其他人保持理智)将您的团队名称存储在一个数组中。

String[] teamNames = new String[] {"Arsenal", "Barcelona", "Bayern Munich", "Chelsea", "Borussia Dortmund", "Galatasaray", "Juventus", "Manchester United", "Milan", "Real Madrid"};

And then replacing the whole if-else for.- 然后替换整个if-else

HomeTeam = teamNames[HomeTeamID];
AwayTeam = teamNames[AwayTeamID];

As a side note, you should stick to java conventions for variable naming, and use lower case camelCase ( homeTeam , awayTeam , homeTeamID , awayTeamId ). 附带说明一下,您应遵循Java约定进行变量命名,并使用小写的camelCase( homeTeamawayTeamhomeTeamIDawayTeamId )。

changed else if to if 改变else if if

try 尝试

import java.util.Random;
/**
 * @author Sertac
 */
public class SoccerSimulator {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int HomeTeamScore = 0;
        int AwayTeamScore = 0;
        Random randomGenerator = new Random();

        String HomeTeam = new String();
        String AwayTeam = new String();
        int HomeTeamID = randomGenerator.nextInt(10);
        int AwayTeamID = randomGenerator.nextInt(10);

        if(HomeTeamID == AwayTeamID){
            while (HomeTeamID != AwayTeamID){
                AwayTeamID = randomGenerator.nextInt(10);
            }
        }

        if(HomeTeamID == 0 || AwayTeamID == 0){
            if(HomeTeamID == 0){
                HomeTeam = "Arsenal";
            }else{
                AwayTeam = "Arsenal";
            }
        }  if(HomeTeamID == 1 || AwayTeamID == 1){
            if(HomeTeamID == 1){
                HomeTeam = "Barcelona";
            }else{
                AwayTeam = "Barcelona";
            }
        }  if(HomeTeamID == 2 || AwayTeamID == 2){
            if(HomeTeamID == 2){
                HomeTeam = "Bayern Munich";
            }else{
                AwayTeam = "Bayern Munich";
            }
        }  if(HomeTeamID == 3 || AwayTeamID == 3){
            if(HomeTeamID == 3){
                HomeTeam = "Chelsea";
            }else{
                AwayTeam = "Chelsea";
            }
        }  if(HomeTeamID == 4 || AwayTeamID == 4){
            if(HomeTeamID == 4){
                HomeTeam = "Borussia Dortmund";
            }else{
                AwayTeam = "Borussia Dortmund";
            }
        }  if(HomeTeamID == 5 || AwayTeamID == 5){
            if(HomeTeamID == 5){
                HomeTeam = "Galatasaray";
            }else{
                AwayTeam = "Galatasaray";
            }
        }  if(HomeTeamID == 6 || AwayTeamID == 6){
            if(HomeTeamID == 6){
                HomeTeam = "Juventus";
            }else{
                AwayTeam = "Juventus";
            }
        }  if(HomeTeamID == 7 || AwayTeamID == 7){
            if(HomeTeamID == 7){
                HomeTeam = "Manchester United";
            }else{
                AwayTeam = "Manchester United";
            }
        }  if(HomeTeamID == 8 || AwayTeamID == 8){
            if(HomeTeamID == 8){
                HomeTeam = "Milan";
            }else{
                AwayTeam = "Milan";
            }
        }  if(HomeTeamID == 9 || AwayTeamID == 9){
            if(HomeTeamID == 9){
                HomeTeam = "Real Madrid";
            }else{
                AwayTeam = "Real Madrid";
            }
        }

        //Generating each random integers in range 0..99 for 90 minutes
        for(int minutes = 0; minutes <= 90; minutes++){
            int randomInt = randomGenerator.nextInt(100);

            //if random int equals 0,1,2 home team scores
            if(randomInt < 3){ HomeTeamScore = HomeTeamScore + 1; }

            //if random int equals 98,99 away team scores
            //home team has 1 more int because playing at home is better
            if(randomInt > 97){ AwayTeamScore = AwayTeamScore + 1; }                         
        }
        System.out.println ("Simulation for match of the week:");
        System.out.println (HomeTeam + " " + HomeTeamScore + " - " + AwayTeamScore + " " + AwayTeam);

        }   
    }

The problem lies here: 问题出在这里:

if(HomeTeamID == 0 || AwayTeamID == 0){
            if(HomeTeamID == 0){
                HomeTeam = "Arsenal";
            }else{
                AwayTeam = "Arsenal";
            }
        } else if(HomeTeamID == 1 || AwayTeamID == 1){
            if(HomeTeamID == 1){
                HomeTeam = "Barcelona";
            }else{
                AwayTeam = "Barcelona";
            }
        } else if(HomeTeamID == 2 || AwayTeamID == 2){
            if(HomeTeamID == 2){
                HomeTeam = "Bayern Munich";
            }else{
                AwayTeam = "Bayern Munich";
            }
        } else if(HomeTeamID == 3 || AwayTeamID == 3){
            if(HomeTeamID == 3){
                HomeTeam = "Chelsea";
            }else{
                AwayTeam = "Chelsea";
            }
        } else if(HomeTeamID == 4 || AwayTeamID == 4){
            if(HomeTeamID == 4){
                HomeTeam = "Borussia Dortmund";
            }else{
                AwayTeam = "Borussia Dortmund";
            }
        } else if(HomeTeamID == 5 || AwayTeamID == 5){
            if(HomeTeamID == 5){
                HomeTeam = "Galatasaray";
            }else{
                AwayTeam = "Galatasaray";
            }
        } else if(HomeTeamID == 6 || AwayTeamID == 6){
            if(HomeTeamID == 6){
                HomeTeam = "Juventus";
            }else{
                AwayTeam = "Juventus";
            }
        } else if(HomeTeamID == 7 || AwayTeamID == 7){
            if(HomeTeamID == 7){
                HomeTeam = "Manchester United";
            }else{
                AwayTeam = "Manchester United";
            }
        } else if(HomeTeamID == 8 || AwayTeamID == 8){
            if(HomeTeamID == 8){
                HomeTeam = "Milan";
            }else{
                AwayTeam = "Milan";
            }
        } else if(HomeTeamID == 9 || AwayTeamID == 9){
            if(HomeTeamID == 9){
                HomeTeam = "Real Madrid";
            }else{
                AwayTeam = "Real Madrid";
            }
        }

U are always assigning only one team, either home or away team since you are using a wrong construction here. U始终只分配一个队,无论是主队还是客队,因为您在这里使用的结构错误。 Try something like: 尝试类似的方法:

switch(HomeTeamID)
{
case 0: HomeTeam = "Arsenal";
        break;
case 1: HomeTeam = "Barcelona";
...
break
}

and same for away team: 与客队相同:

switch(HomeTeamID)
{
case 0: AwayTeam = "Arsenal";
        break;
case 1: AwayTeam = "Barcelona";
...
break
}

And you should check the java code conventions..The variable names should begin with a lowercase. 并且您应该检查Java代码约定。.变量名应以小写字母开头。

如果用if替换else,则代码应该可以正常工作。

I would start from the very beginning. 我将从一开始就开始。 What is it that you are trying to do. 您正在尝试做什么。

Given some teams you want to select two random teams to play each other, one home and one away. 给定一些团队,您想选择两个随机的团队互相比赛,一个主场一个。

Currently you are selecting two random int ids from a Random and using those to lookup teams in an implied array of teams. 当前,您正在从“ Random中选择两个随机int id,并使用它们在隐含的团队数组中查找团队。

So, first go with @ssantos' suggestion - make the array explicit and simply get the index from there. 因此,首先使用@ssantos的建议-使数组明确,然后从那里简单地获取索引。

But, we have an issue - a team cannot play itself. 但是,我们有一个问题-团队无法发挥自己的作用。 So in fact we need a slightly different approach. 因此,实际上我们需要一种略有不同的方法。 What you need to do is take the array of all teams, shuffle it, and then read pairs out of the array. 您需要做的是将所有团队组成的数组,将其洗牌,然后从数组中读取对。 This is in fact how selection tends to work in tournaments. 实际上,这就是选择倾向于在锦标赛中起作用的方式。

Here is my suggested code: 这是我建议的代码:

private static final String[] TEAM_NAMES = new String[]{"Arsenal", "Barcelona", "Bayern Munich", "Chelsea", "Borussia Dortmund", "Galatasaray", "Juventus", "Manchester United", "Milan", "Real Madrid"};
private static final Random RANDOM = new Random();

public static void main(final String args[]) {
    List<String> teams = new ArrayList<>(Arrays.asList(TEAM_NAMES));
    while (teams.size() > 1) {
        teams = playRound(teams);
    }
    System.out.println("The champion is " + teams);
}

public static List<String> playRound(final List<String> teams) {
    Collections.shuffle(teams);
    final Iterator<String> teamsIter = teams.iterator();
    final List<String> winners = new ArrayList<>();
    while (teamsIter.hasNext()) {
        final String winner = play(teamsIter.next(), teamsIter.next());
        winners.add(winner);
    }
    return winners;
}

public static String play(final String team1, final String team2) {
    return RANDOM.nextBoolean() ? team1 : team2;
}

From the top: 从顶部:

First we declare out constants - the array of teams and the Random instance. 首先,我们声明常量-团队数组和Random实例。 These variables are static final so they are named in BLOCK_CAPITALS . 这些变量是static final变量,因此在BLOCK_CAPITALS中命名。

main 主要

Next we have out main method. 接下来,我们得出main方法。 This method takes the teams and reads them into a List . 此方法将团队带入List We need to make a copy of the teams so that we don't mess around with the teams array. 我们需要复制团队,以免弄乱团队数组。 A List is a more flexible structure, as you'll see later. List是一种更灵活的结构,您将在后面看到。 Also note that you need a power of two of teams - if teams play in pairs then you need a number divisible by two in each round. 还要注意,您需要两支球队的力量-如果两队成对比赛,那么您需要在每一回合中将数字除以2。

The method now goes into a while loop. 该方法现在进入while循环。 This structure keeps playing all the winning teams from each round against each other until an ultimate winner is reached - the tournament champion. 这种结构可以让每一轮的所有获胜球队互相对抗,直到获得最终冠军-锦标赛冠军。 It prints out the champion's name. 它打印出冠军的名字。

playRound playRound

This is where the magic happens. 这就是魔术发生的地方。

The method first shuffles incoming teams so that they are retrieved at random. 该方法首先对进入的团队进行shuffles以便随机检索它们。 It then gets the Iterator for the List - this allows you to walk along the List element by element. 然后,它获取ListIterator -这使您可以逐元素遍历List元素。 This is also where the error will be thrown if there isn't an even number of teams - the second next() will throw a NoSuchElementException . 如果没有偶数的团队,这也是引发错误的地方-第二个next()将引发NoSuchElementException

The method then goes into another while loop - while the Iterator isn't empty it calls play with two teams. 然后,该方法进入另一个while循环-而Iterator不为空,它调用play两支球队。 It puts the winning teams into the winners List . 它将获胜团队放入winners List This is the List that is returned in the end. 这是最后返回的List

Not that a List has an add method so that you can fill it dynamically - this is different to an array which has a fixed size. List不是具有add方法,因此您可以动态填充它-这与具有固定大小的数组不同。

play

This is where your actual simulation would go. 这就是您实际的模拟的去向。 Currently it selects a winner at random - you could put your current method in. 目前,它随机选择一个获胜者-您可以输入当前的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM