Results 1 to 2 of 2
- 06-29-2011, 01:43 AM #1
Member
- Join Date
- Jun 2011
- Posts
- 1
- Rep Power
- 0
Checking a string var to an actually string?
So, I made a random number generator/guessing game just for fun and practice. But I'm stuck.. at the end of the program if you guessed wrong it asks you if you want to try again. I have a string var and I'm trying to check if it is equal to the word "Yes", and if it is then run the program again. But it always does the else statement of the if function, even if I type the word yes.
EDIT: I figured out I need to use ".equals(object)" to compare the contents of my String.Java Code:import java.util.Scanner; public class RandomNumber { //Yes, No Vars public String yesVar = "Yes"; public String noVar = "No"; //User Input Scanner scanner = new Scanner(System.in); //Try again variables public boolean playAgain = false; public String startOverAnswer; public void pickNumber() { //Random Number int number = (int) (Math.random()*10)+1; //Get user guess and parse the guess to an int System.out.print("Your guess: "); String guess = scanner.nextLine(); int guessFinal = Integer.parseInt(guess); //Check guess if(guessFinal == number) { System.out.println("Nice guess, you got it RIGHT!"); } else { System.out.println("I know, it's hard. But you got it WRONG!"); System.out.println(""); System.out.println("Would you like to try again? (Yes or No): "); String startOverAnswer = scanner.nextLine(); //Start over? if(startOverAnswer == "Yes"){ pickNumber(); } System.out.println("Ended"); } } }
There's also a class that runs the file, but I guess you guys don't need that code.Last edited by DoubleElite; 06-29-2011 at 01:47 AM. Reason: FIXED
- 06-29-2011, 03:03 AM #2
Similar Threads
-
Checking The Contents of a String
By jayragz in forum New To JavaReplies: 7Last Post: 05-26-2011, 10:15 AM -
Checking If A String Contains Symbols
By SwissR in forum New To JavaReplies: 7Last Post: 07-27-2010, 09:07 AM -
checking for ints in a String
By SteroidalPsycho in forum New To JavaReplies: 1Last Post: 03-26-2010, 06:09 PM -
Help with checking for a certain format in a String
By SteroidalPsycho in forum New To JavaReplies: 2Last Post: 03-26-2010, 04:56 AM -
spliting a string and checking each token's format
By Implode in forum New To JavaReplies: 1Last Post: 10-18-2009, 08:41 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks