Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

130 HOUR 10:Creating Your First Object


variable is to use a string in a numeric expression. When the string’s value
could become an integer, this can be done using the parseInt()method of
the Integerclass, as in this example:
String count = “25”;
int myCount = Integer.parseInt(count);

This converts a string with the text “25” into an integer with the value 25.
If the string value was not a valid integer, the conversion would not work.
The next project you create is an application that converts a string value in
a command-line argument to a numeric value, a common technique when
you’re taking input from a user at the command line.
Return to your Java24 project in NetBeans, choose File, New File, and then
create a new Empty Java File named NewRoot. Enter Listing 10.1 in the
source editor and remember to save the file.

LISTING 10.1 The Full Text of NewRoot.java
1: classNewRoot {
2: public static voidmain(String[] args) {
3: int number = 100;
4: if (args.length> 0) {
5: number = Integer.parseInt(args[0]);
6: }
7: System.out.println(“The square root of “
8: + number
9: + “ is “
10: + Math.sqrt(number) );
11: }
12: }

Before you run the program, you must configure NetBeans to run it with a
command-line argument. Choose the menu command Run, Set Project
Configuration, Customize. The Project Properties window opens. Enter
NewRootas the Main Class and 169 in the Arguments field. Click OK to
close the dialog.
To run the program, choose Run, Run Main Project (instead of Run, Run
File). The program displays the number and its square root, as shown in
Figure 10.3.
The NewRootapplication is an expansion of an earlier tutorial from Hour 4,
“Understanding How Java Programs Work,” that displayed the square root
of the integer 225.
Free download pdf