Question

I'm making a quiz like game. I have two arrays (One with the states and the other with the capitals). Basically it asks the user what capital goes with a random state. I want that if the user inputs the correct state for it to be like nice job or whatever but I do not know how to compare the user input to the specific array compartment. I tried .contains but no avail... Any help?

My bad - I'm using Java

For Example

if(guess.equals(capitals[random]))

where guess is the string and capitals is the array and random is the random number

Était-ce utile?

La solution 2

Logic similar to this should work. You want to save the user input to a String variable, and then compare it to an n sized array.

for(int i=0; i<arrayName.length();i++)
{
     if(userinputString.equalsIgnorCase(arrayName[i])
     {
          System.out.println("HUrray!");
     }//end if

}//end for

Ok so you are somehow producing a random number, and then need to compare the input to the String in the capital Array for that random number/

Im assuming the arrays are ordered such that capitals[10] gives you the capital for states[10].

If so, just save the index to a variable.

int ranNum=RandomNumFunction();

Then just see if

if(capitals[ranNum].equalsIgnoreCase(userInput))
//do something

Autres conseils

Basically you want a mapping String -> String (State -> Capital). This could be done using a Map<String, String> or by creating a State class which will contains its name and its capital as attributes.

But to my mind, the best option is to use an enum as you know that there is 50 states. Here's a small example.

public class Test {  

    static final State[] states = State.values();
    static Random r = new Random();
    static Scanner sc = new Scanner(System.in);

    public static void main (String[] args){
        State random = states[r.nextInt(states.length)];
        random.askQuestion();
        String answer = sc.nextLine();
        if(answer.equals(random.getCapital())){
            System.out.println("Congrats");
        } else {
            System.out.println("Not really");
        }       
    }   
}

enum State {
    //Some states, add the other ones
    ALABAMA("Montgomery"),
    ALASKA("Juneau");

    private final String capital;

    private State(String capital){
        this.capital = capital;
    }

    public String getCapital(){
        return this.capital;
    }

    public void askQuestion(){
        System.out.println("What capital goes with "+this.name()+"?");
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top