Java Reference
In-Depth Information
An example can help to clarify this. Let's assume that you want to make a class that accepts lines
from
System.in
and then shows the reversed line on
System.out
. When a palindrome is given,
however (a line that reads the same forward or reversed), we'll also show a toy “warning” on
System.err
. When a blank line is given, execution is stopped. The final class looks like this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LineReverser {
public static void main(String[] args) {
try(
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
) {
String line = null;
while (true) {
line = reader.readLine();
if (line == null ║ "".equals(line))
break;
String reverse = new StringBuilder(line).reverse().toString();
System.out.println(reverse);
if (line.equals(reverse))
System.err.format("The string '%s' is a palindrome!%n", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Take some time to execute this
class and familiarize yourself
with the code. Try to enter a pal-
indrome such as “amoreroma”
and see what happens.
Now, we will take this a step
further. Right-click on the
LineReverser
class in Eclipse
and choose Export. Next, select
Runnable JAR File. See Figure 8-5.
In the next screen, select
LineReverser
as the “launch
configuration” (this requires
that you ran the class in Eclipse
at least once). Set the Export
Destination to
linereverser.
jar
on your desktop.
fiGure 8-5
Search WWH ::
Custom Search