Considering that ! is just one character, there's not much point in having a separate inequality test function that would just return the negation of the equality function.
So no.
Java string.equals function for inequality?
-
24-06-2022 - |
سؤال
This code compares text entered by the user (userText) with a keyword (endProgram). When the user enters the word exit, the program will complete and close.
public static void main(String[] args) {
String endProgram = "exit";
String userInput;
java.util.Scanner input = new java.util.Scanner(System.in);
do {
userInput = input.nextLine();
} while ( !(userInput.equals(endProgram)) );
}
Is there a better way to write the code within the while parenthesis?
That is, instead of using !(String.equals(String))
is there another function to compare inequality?
المحلول
نصائح أخرى
You can use String.compareTo(String)
which would return 0
when Strings are the same. It is more general than String.equals(String)
as it performs lexical comparison and can be used for ordering (i.e. "a" < "b"
). It has an compareToIgnoreCase()
variant which would be better in your case as "EXIT"
sounds just as valid as "exit"
.
The equals()
method is actually performing comparison on an Object
, not a String
(though it will fail if the Object
is not an instance of String
). Its equalsIgnoreCase()
variant though, is taking a String
as a parameter.
If you don't like the "equal approach" (but the code you just wrote is right), you could use an integer
as exit condition.
In that case, I suggest the use of hasNextInt()
.