Sunday, February 25, 2018

Checking String for Equality

Note: Your feedback on how to improve this post is most welcome.

For comparing String values, ==, !=, >, < are not appropriate. These are better suited to numbers.

For Strings, use something like
Scanner sc = new Scanner(System.in);
System.out.println("Please type + or - or *");
String operator = sc.next();
if (operator.equals ("+"))
{
     System.out.println("you gave a plus sign");
}
else
{
     System.out.println("you gave something else");
}


Recommended reading:

for regular students:
http://alvinalexander.com/java/edu/qanda/pjqa00001.shtml

for advanced learners:
http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html
https://www.javaworld.com/article/2077355/core-java/don-t-be-strung-along.html
https://www.baeldung.com/java-compare-strings


Want to learn more about characters and strings?
https://www.javaworld.com/article/2074031/core-java/jdk-7--java-switching-on-strings-is-here.html
https://www.javaworld.com/article/2074647/core-java/core-java-java-s-character-and-assorted-string-classes-support-text-processing.html

No comments: