Java Reference
In-Depth Information
}
}
Given that the “for each” loop has been in the language for ages, you might be excused for
expecting to be able to write something like for (char ch : myString) {…} . Unfortu-
nately, this does not work. But you can use myString.toCharArray() as in the following:
public
public class
class ForEachChar
ForEachChar {
public
public static
void main ( String [] args ) {
String s = "Hello world" ;
// for (char ch : s) {...} Does not work, in Java 7
for
static void
for ( char
char ch : s . toCharArray ()) {
System . out . println ( ch );
}
}
}
A “checksum” is a numeric quantity representing and confirming the contents of a file. If
you transmit the checksum of a file separately from the contents, a recipient can checksum
the file—assuming the algorithm is known—and verify that the file was received intact.
Example 3-4 shows the simplest possible checksum, computed just by adding the numeric
values of each character. Note that on files, it does not include the values of the newline char-
acters; in order to fix this, retrieve System.getProperty("line.separator"); and add its
character value(s) into the sum at the end of each line. Or give up on line mode and read the
file a character at a time.
Example 3-4. CheckSum.java
/** CheckSum one text file, given an open BufferedReader.
* Checksumm does not include line endings, so will give the
* same value for given text on any platform. Do not use
* on binary files!
*/
public
public static
static int
int process ( BufferedReader is ) {
int
int sum = 0 ;
try
try {
String inputLine ;
while
while (( inputLine = is . readLine ()) != null
null ) {
int
int i ;
for
for ( i = 0 ; i < inputLine . length (); i ++) {
sum += inputLine . charAt ( i );
Search WWH ::




Custom Search