23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

that <strong>in</strong>put <strong>and</strong> <strong>in</strong>form the user that he or she has quit. The follow<strong>in</strong>g example<br />

illustrates this case:<br />

public void getUserInput() {<br />

}<br />

Str<strong>in</strong>g <strong>in</strong>put;<br />

do {<br />

<strong>in</strong>put = getInputStr<strong>in</strong>g();<br />

h<strong>and</strong>leInput(<strong>in</strong>put);<br />

} while (<strong>in</strong>put.length()>0);<br />

Notice the exit condition for the above example. Specifically, it is written to be<br />

consistent with the rule <strong>in</strong> <strong>Java</strong> that do-while loops exit when the condition is<br />

not true (unlike the repeat-until construct used <strong>in</strong> other languages).<br />

1.4.3 Explicit Control-Flow Statements<br />

<strong>Java</strong> also provides statements that allow for explicit change <strong>in</strong> the flow of control of<br />

a program.<br />

Return<strong>in</strong>g from a Method<br />

If a <strong>Java</strong> method is declared with a return type of void, then flow of control<br />

returns when it reaches the last l<strong>in</strong>e of code <strong>in</strong> the method or when it encounters a<br />

return statement with no argument. If a method is declared with a return type,<br />

however, the method is a function <strong>and</strong> it must exit by return<strong>in</strong>g the function's<br />

value as an argument to a return statement. The follow<strong>in</strong>g (correct) example<br />

illustrates return<strong>in</strong>g from a function:<br />

// Check for a specific birthday<br />

public boolean checkBDay (<strong>in</strong>t date) {<br />

if (date == Birthdays.MIKES_BDAY) {<br />

}<br />

return true;<br />

return false;<br />

57

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!