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.

An Output Example<br />

Consider, for example, the follow<strong>in</strong>g code fragment:<br />

System.out.pr<strong>in</strong>t("<strong>Java</strong> values: ");<br />

System.out.pr<strong>in</strong>t(3.1415);<br />

System.out.pr<strong>in</strong>t(',');<br />

System.out.pr<strong>in</strong>t(15);<br />

System.out.pr<strong>in</strong>tln(" (double,char,<strong>in</strong>t) .");<br />

When executed, this fragment will output the follow<strong>in</strong>g <strong>in</strong> the <strong>Java</strong> console<br />

w<strong>in</strong>dow: <strong>Java</strong> values: 3.1415,15 (double,char,<strong>in</strong>t).<br />

Simple Input Us<strong>in</strong>g the java.util.Scanner Class<br />

Just as there is a special object for perform<strong>in</strong>g output to the <strong>Java</strong> console w<strong>in</strong>dow,<br />

there is also a special object, called System.<strong>in</strong>, for perform<strong>in</strong>g <strong>in</strong>put from the<br />

<strong>Java</strong> console w<strong>in</strong>dow. Technically, the <strong>in</strong>put is actually com<strong>in</strong>g from the "st<strong>and</strong>ard<br />

<strong>in</strong>put" device, which by default is the computer keyboard echo<strong>in</strong>g its characters <strong>in</strong><br />

the <strong>Java</strong> console. The System.<strong>in</strong> object is an object associated with the st<strong>and</strong>ard<br />

<strong>in</strong>put device. A simple way of read<strong>in</strong>g <strong>in</strong>put with this object is to use it to create a<br />

Scanner object, us<strong>in</strong>g the expression<br />

new Scanner(System.<strong>in</strong>)<br />

The Scanner class has a number of convenient <strong>in</strong>cluded methods that read from<br />

the given <strong>in</strong>put stream. For example, the follow<strong>in</strong>g program uses a Scanner object<br />

to process <strong>in</strong>put:<br />

import java.io.*;<br />

import java.util.Scanner;<br />

public class InputExample {<br />

public static void ma<strong>in</strong>(Str<strong>in</strong>g args[]) throws<br />

IOException {<br />

Scanner s = new Scanner(System.<strong>in</strong>);<br />

System.out.pr<strong>in</strong>t("Enter your height <strong>in</strong> centimeters:<br />

");<br />

66

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

Saved successfully!

Ooh no, something went wrong!