Java Reference
In-Depth Information
private
private static
static
Number NAN
=
new
new
Double
(
Double
.
NaN
);
/* Process one String, returning it as a Number subclass
* Does not require the GUI.
*/
public
public static
static
Number
process
(
String s
) {
iif
(
s
.
matches
(
"[+-]*\\d*\\.\\d+[dDeEfF]*"
)) {
try
try
{
double
double
dValue
=
Double
.
parseDouble
(
s
);
System
.
out
.
println
(
"It's a double: "
+
dValue
);
return
return
Double
.
valueOf
(
dValue
);
}
catch
catch
(
NumberFormatException e
) {
System
.
out
.
println
(
"Invalid double: "
+
s
);
return
return
NAN
;
}
}
else
else
// did not contain . d e or f, so try as int.
try
try
{
int
int
iValue
=
Integer
.
parseInt
(
s
);
System
.
out
.
println
(
"It's an int: "
+
iValue
);
return
return
Integer
.
valueOf
(
iValue
);
}
catch
catch
(
NumberFormatException e2
) {
System
.
out
.
println
(
"Not a number: "
+
s
);
return
return
NAN
;
}
}
public
public static
static
void
void
main
(
String
[]
ap
) {
new
new
GetNumber
().
setVisible
(
true
true
);
}
}
See Also