Let
us pretend to be a nurse. (Medical insurance
is so high that you don't want to be sick. So do exercsises!) You
take kids ear temperature to see if they have fever or not. If thermometer
reading is greater than 100.4, you print out "Beep, Beep, Beep!",
other wise you print out "No fever".
Since a nurse could take a lot of temperature.
We also don't want to define a lot of double variables
in our code. Instead, we use only one variable
to store the temperature reading.
I will show you one trick: accept ear temperature reading from command
line.
Take parameters from command
line
When we try to run a program, we type in
command line: java program.
If you type: java program arg0
arg1 arg2 arg3 arg4...., JAVA boy will transfer arg0
arg1 arg2 arg3 arg4... into main method.
public static void main(String[]
args)
See? All you typed arg0 arg1 arg2
arg3 arg4.. will be in the
array String[]
args. Remember, JAVA boy counts everything
start from 0.
Here is our thermometer code:
class thermometer
{
public static void main(String[] args)
{
double temperature;
temperature=Double.parseDouble(args[0]);
if(temperature>100.4)
System.out.println ("Beep Beep Beep");
else
System.out.println("No fever.");
}
}
Save the above code as thermometer.java.
Compile it: javac thermometer.java. Then run: java
thermometer 102.3. 102.3 is
the temperature. In the code, args[0]="102.3". Double.parseDouble is
new thing to you. It converts a string to a double value. Double is
a class and parseDouble is
its method. It is just one handy tools JAVA boy provides.
Try type: java thermometer abc
What did you see? Look like the following? I will answer you in class
9.
Exception in thread "main" java.lang.NumberFormatException:
For input string: "abc"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
at java.lang.Double.parseDouble(Double.java:482)
at thermometer.main(thermometer.java:8)
|