Java Reference
In-Depth Information
TABLE 2 . 4 : Comparison of String elements.
What we want to write What we must write
s1.equals(s2) or s1.compareTo(s2)==0
7. If s is equal to "F" , then tell the user the grade is lower than 60.
The first two lines of the algorithm can be implemented as follows.
System. out . print ( "Enter letter grade: " );
Scanner keyboard = new Scanner(System. in) ;
String s = keyboard . next () ;
The code uses the next method. It returns the next string that is typed. Note that Java
does not have a nextChar method that reads a single character from the keyboard. The
next method reads characters from the input until a delimiter, such as space or new line, is
reached. If we want to read a whole line from the keyboard, then we can call the nextLine
method. Note as well that a String behaves similar to a primitive type (e.g., integer). We
can define the string variable s by simply typing the following command.
String s ;
Similarly, we can assign a value to a string as follows.
s= "cat" ;
Remember that string literals are surrounded by double quotes. One major difference
between a String and the other primitive types is that strings cannot be compared the
same way as integers. You can still compare two strings for equality, but you need to use
the equals method instead of “==”. Similarly, you can compare two strings relative to their
lexicographical ordering. A lexicographical ordering of two strings relates to how they will
appear in a dictionary. For example, the string "abc" will appear before the string "de" .
Note that every character has an ASCII code; see Figure 2.8. Two strings are compared
by comparing the ASCII code of their first character. If the first characters have the same
code, then the ASCII code of the second characters are compared and so on. The compareTo
method is used to compare two strings. Table 2.4 summarizes the two methods.
Note that the compareTo method returns a positive integer when the first string is bigger,
0 when the two strings are the same, and a negative integer when the first string is smaller.
Therefore, in order to check if two strings are the same, we can either write s1.equals(s2)
or s1.compareTo(s2) == 0 .
Going back to our original problem, we can check the value of the string s as follows.
if (s.equals( "A" )) {
System. out . println ( "Your grade is between 90 and 100" );
if (s.equals( "B" )) {
System. out . println ( "Your grade is between 80 and 89" );
if (s.equals( "C" )) {
System. out . println ( "Your grade is between 70 and 79" );
if (s.equals( "D" )) {
System. out . println ( "Your grade is between 60 and 69" );
Search WWH ::

Custom Search