+ 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!"); }

2nd Jun 2017, 3:25 PM
Jacob Braun
Jacob Braun - avatar
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.
2nd Jun 2017, 3:33 PM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 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.
2nd Jun 2017, 3:37 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Thank you both very much! Everyone on the forums is really helpful.
2nd Jun 2017, 3:38 PM
Jacob Braun
Jacob Braun - avatar