+ 1
User Input for Country Guesser
In my country guesser, I've worked out how to get hints up and running. But, I need the user to actually guess the country that is randomly generated. I set up a countryGuess variable, but if I compare it and the program's generated country, it cannot compare strings and scanners. How can I get user Input? Code: int random = (int)(Math.random()*(countries.length-1)); String mysteryCountry = countries[random]; System.out.println(mysteryCountry); System.out.println("Guess A Country!"); Scanner countryGuess = new Scanner(system.in); if (countryGuess == mysteryCountry){ System.out.println("Correct!"); }else{ System.out.println("Incorrect, Try Again!"); }
3 Antworten
+ 4
There is a method nextLine() to read a line, and returns the line in String. Before if statement, declare a new String and initialize with countryGuess.nextLine(). Then compare your new String with mysteryCountry with equals(), not == in the condition of if statement.
+ 3
The scanner isn't the input, the scanner is an object that can read input.
Use:
String input = countryGuess.next();
Or, use nextLine();
Since strings are objects comparing with == may have different results .
So, use:
input.equals(mysteryCounty)
As the condition for the if statement.
equals() will compare character by character to assure that they are equal.
+ 1
Thank you both very much! Everyone on the forums is really helpful.