物件導向程式設計
|
2.10 字串轉為數值 |
|
|
授課教師:陳慶瀚 WWW : http://www.miat.ee.isu.edu.tw/java E-mail : pierre@isu.edu.tw |
|
When processing user input it is often necessary to convert a String that the user enters into an int . The syntax is
straightforward. It requires using the static Integer.valueOf(String
s) and intValue() methods from the java.lang.Integer
class. To convert the String "22" into the
int 22 you would write
Doubles, floats and longs are converted
similarly. To convert a String like "22" into the long value 22 you would
write
To convert
The various valueOf() methods are
relatively intelligent and can handle plus and minus signs, exponents, and most
other common number formats. However if you pass one something completely
non-numeric like "pretty in pink," it will throw a
NumberFormatException . You haven't learned how to handle exceptions
yet, so try to avoid passing theses methods non-numeric data.
You can now rewrite the E = mc2 program to accept the mass in kilograms as user input from the command line. Many of the exercises will be similar.
Here's the output:
課堂練習: 請將上述程式(mc2)的質量輸入改由ConsoleReader執行。(請參考第一章範例三、在console模式進行數值輸入輸出)
|
||
物件導向程式設計 義守大學電機系 陳慶瀚 2001.10.02 |