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.

float height = s.nextFloat();<br />

System.out.pr<strong>in</strong>t("Enter your weight <strong>in</strong> kilograms: ");<br />

float weight = s.nextFloat();<br />

float bmi = weight/(height*height)*10000;<br />

System.out.pr<strong>in</strong>tln("Your body mass <strong>in</strong>dex is " + bmi +<br />

".");<br />

}<br />

}<br />

When executed, this program could produce the follow<strong>in</strong>g on the <strong>Java</strong> console:<br />

Enter your height <strong>in</strong> centimeters:180<br />

Enter your weight <strong>in</strong> kilograms: 80.5<br />

Your body mass <strong>in</strong>dex is 24.84568.<br />

java.util.Scanner Methods<br />

The Scanner class reads the <strong>in</strong>put stream <strong>and</strong> divides it <strong>in</strong>to tokens, which are<br />

contiguous str<strong>in</strong>gs of characters separated by delimiters, which are special<br />

separat<strong>in</strong>g characters. The default delimiter is whitespace, that is, tokens are<br />

separated by str<strong>in</strong>gs of spaces, tabs, <strong>and</strong> newl<strong>in</strong>es, by default. Tokens can either be<br />

read immediately as str<strong>in</strong>gs or a Scanner object can convert a token to a base<br />

type, if the token is <strong>in</strong> the right syntax. Specifically, the Scanner class <strong>in</strong>cludes<br />

the follow<strong>in</strong>g methods for deal<strong>in</strong>g with tokens:<br />

hasNext(): Return true if <strong>and</strong> only if there is another token <strong>in</strong> the <strong>in</strong>put<br />

stream.<br />

next(): Return the next token str<strong>in</strong>g <strong>in</strong> the <strong>in</strong>put stream; generate an error<br />

if there are no more tokens left.<br />

hasNextType(): Return true if <strong>and</strong> only if there is another token <strong>in</strong> the <strong>in</strong>put<br />

stream <strong>and</strong> it can be <strong>in</strong>terpreted as the correspond<strong>in</strong>g base type, Type, where Type<br />

can be Boolean, Byte, Double, Float, Int, Long, or Short.<br />

nextType(): Return the next token <strong>in</strong> the <strong>in</strong>put stream, returned as the base<br />

type correspond<strong>in</strong>g to Type; generate an error if there are no more tokens left or if<br />

the next token cannot be <strong>in</strong>terpreted as a base type correspond<strong>in</strong>g to Type.<br />

67

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

Saved successfully!

Ooh no, something went wrong!