简体   繁体   中英

How do I compare user string input to the string in an entire array?

In my program I have an array with team names and what I want to do is collect user input that checks if the input matches any of the team names in the array. I can only get it to check one string in the array at a time if i put in the arguement of the if statement:

if(teamName.equals(teams[0])

. But I want to check all the strings in the array rather than one at a time

    Scanner input = new Scanner(System.in);

    String[] teams = new String [20];
    teams[0] = "Arsenal";
    teams[1] = "Aston Villa";
    teams[2] = "Burnley";
    teams[3] = "Chelsea";
    teams[4] = "Crystal Palace";
    teams[5] = "Everton";
    teams[6] = "Hull City";
    teams[7] = "Leicester City";
    teams[8] = "Liverpool";
    teams[9] = "Manchester City";
    teams[10] = "Manchester United";
    teams[11] = "Newcastle United";
    teams[12] = "QPR";
    teams[13] = "Southampton";
    teams[14] = "Sunderland";
    teams[15] = "Spurs";
    teams[16] = "Stoke";
    teams[17] = "Swansea";
    teams[18] = "West Ham";
    teams[19] = "West Brom";

System.out.println("Please enter a team: ");
    String teamName = input.nextLine();

    if(teamName.equals(teams)) {
            System.out.println("You like: " + teamName);
    }
    else {
        System.out.println("Who?");
    }
}   

Using java8, this would be a possible solution:

 if(Arrays.stream(teams).anyMatch(t -> t.equals(teamName))) {
     System.out.println("You like: " + teamName);
 } else {
     System.out.println("Who?");
 }

Just put them in a Set and use the contains method.

So make the following changes:

Set<String> teamSet = new TreeSet<>();
Collections.addAll(teamSet, teams);

System.out.println("Please enter a team: ");
String teamName = input.nextLine();

if (teamSet.contains(teamName)) {
    System.out.println("You like: " + teamName);
} else {
    System.out.println("Who?");
}

add this method to your code

public boolean arrayContainsTeam(String team)
{
    boolean hasTeam = false;
    for(String aTeam:teams) {
         if(aTeam.equals(team)) {
              return(true);
         }
    }
    return(false);
}

and then replace

if(teamName.equals(teams)) {
        System.out.println("You like: " + teamName);
}
else {
    System.out.println("Who?");
}

with

if(arrayContainsTeam(teamName)) {
        System.out.println("You like: " + teamName);
}
else {
    System.out.println("Who?");
}

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