简体   繁体   中英

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. 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

or: 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. 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.-

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 ).

changed else if to 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. 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.

如果用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.

So, first go with @ssantos' suggestion - make the array explicit and simply get the index from there.

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. These variables are static final so they are named in BLOCK_CAPITALS .

main

Next we have out main method. This method takes the teams and reads them into a 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. 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.

The method now goes into a while loop. 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

This is where the magic happens.

The method first shuffles incoming teams so that they are retrieved at random. It then gets the Iterator for the List - this allows you to walk along the List element by element. 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 .

The method then goes into another while loop - while the Iterator isn't empty it calls play with two teams. It puts the winning teams into the winners List . This is the List that is returned in the end.

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.

play

This is where your actual simulation would go. Currently it selects a winner at random - you could put your current method in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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