Java Reference
In-Depth Information
Exercise 2.77 The String class defines a length accessor method with the following
* Return the number of characters in this string.
public int length()
so the following is an example of its use with the String variable fullName :
Add conditional statements to the constructor of Student to print an error message if
either the length of the fullName parameter is less than four characters or the length of the
studentId parameter is less than three characters. However, the constructor should still
use those parameters to set the name and id fields, even if the error message is printed.
Hint: Use if statements of the following form (that is, having no else part) to print the error
if( perform a test on one of the parameters ) {
Print an error message if the test gave a true result
See Appendix D for further details of the different types of if statements, if necessary.
Exercise 2.78 Challenge exercise Modify the getLoginName method of Student so
that it always generates a login name, even if either the name or the id field is not strictly long
enough. For strings shorter than the required length, use the whole string.
Experimenting with expressions: the Code Pad
In the previous sections, we have seen various expressions to achieve various computations,
such as the total + price calculation in the ticket machine and the name.substring(0,4)
expression in the Student class.
In the remainder of this topic, we shall encounter many more such operations, sometimes
written with operator symbols (such as “+”) and sometimes written as method calls (such as
substring ). When we encounter new operators and methods, it often helps to try out with dif-
ferent examples what they do.
The Code Pad, which we have briefly used in Chapter 1, can help us experiment with Java
expressions (Figure 2.6). Here, we can type in expressions, which will then be immediately
evaluated and the results displayed. This is very helpful for trying out new operators and
Search WWH ::

Custom Search