Results 1 to 4 of 4
Thread: Comparison of Strings
- 02-10-2008, 06:13 PM #1
Member
- Join Date
- Feb 2008
- Posts
- 2
- Rep Power
- 0
Comparison of Strings
I'm making a java console program, I'm taking input from the user however I want the program to only succeed if the selection given (string) is valid to the choices purposed from the console.
Since I had problems using the != operator not working when comparing a string (nightmare), for the moment of learning I'm using the equals method, my question is what is the alternative method to equals?Java Code:printGameMenu(); do { userChoice = getInput("Please make a selection"); } while("".equals(userChoice));
I need this while loop to continue iterating WHILE the input is not equal to "q" or "p"
q for quitting the program and p for playing the game.
I need the opposite method to equals.Last edited by Cero.Uno; 02-10-2008 at 06:17 PM.
- 02-10-2008, 07:54 PM #2
Member
- Join Date
- Dec 2007
- Posts
- 21
- Rep Power
- 0
Last edited by hey; 02-10-2008 at 08:03 PM.
- 02-10-2008, 08:53 PM #3
Boolean variables
Hello Cero.Uno
You can solve this problem simply by using boolean variables. The String.equals() method returns a boolean result of true if your Strings are equal in value.
This code uses the logic operators || and ==. Google logic operators in Java, to find out more.Java Code:boolean loop = true; do{ userChoice = getInput("Please make a selection"); boolean quit = userChoice.equals("q"); boolean play = userChoice.equals("p"); loop = (quit [COLOR="RoyalBlue"]||[/COLOR] play) [COLOR="SeaGreen"]==[/COLOR] false; while (loop [COLOR="SeaGreen"]==[/COLOR] true);
Good luck. ;)Eyes dwelling into the past are blind to what lies in the future. Step carefully.
- 02-11-2008, 02:46 AM #4
Dead easy, just put the '!' before your condition. For example:
The count is there just to stop the infinite while loop that killed my computer!Java Code:public class TestApp { public static void main(String[] args) { int count = 0; System.out.println("Starting program"); String testString1 = "hello"; String testString2 = "world"; while(!testString1.equals(testString2) && count != 2000) { count++; System.out.println("Number "+count+" This means it is not equal"); } } }
Similar Threads
-
Subtracting Strings
By ravian in forum New To JavaReplies: 7Last Post: 10-08-2009, 06:26 PM -
String comparison
By abhiN in forum New To JavaReplies: 2Last Post: 04-09-2008, 04:47 AM -
Date comparison
By Rageagainst20 in forum New To JavaReplies: 0Last Post: 12-19-2007, 06:34 PM -
Parsing Dates for Comparison
By Rageagainst20 in forum New To JavaReplies: 1Last Post: 12-19-2007, 05:50 AM -
String comparison
By sireesha in forum New To JavaReplies: 1Last Post: 12-18-2007, 12:16 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks