String Conversion
Java has a number of convenient methods for converting strings to other types of data.
| AllConv.java |
| 1 | public class AllConv { |
| 2 | public static void main(String[] args) { |
| 3 | int i = Integer.parseInt("3"); |
| 4 | short s = Short.parseShort("3"); |
| 5 | long l = Long.parseLong("39088825235"); |
| 6 | float f = Float.parseFloat("3.2"); |
| 7 | double d = Double.parseDouble("1.9e-2"); |
| 8 | boolean b = Boolean.parseBoolean("true"); |
| 9 | byte y = Byte.parseByte("-127"); |
| 10 | char c = "a".charAt(0); // character is special |
| 11 | } |
| 12 | } |
$ javac AllConv.java
| $ java AllConv
|
We can combine this knowledge with what we know about loops and the
command line arguments to produce a program which adds one to each
value the user supplies.
| IntConv.java |
| 1 | public class IntConv { |
| 2 | public static void main(String[] args) { |
| 3 | for(int i=0;i<args.length;i++) { |
| 4 | int n = Integer.parseInt(args[i]); |
| 5 | n++; |
| 6 | System.out.println("n="+n); |
| 7 | } |
| 8 | } |
| 9 | } |
$ javac IntConv.java
| $ java IntConv 1 9 100
n=2
n=10
n=101
|
|