Talk:Java Training Course/JT04: Difference between revisions
Jump to navigation
Jump to search
imported>Gfis No edit summary |
imported>Gfis No edit summary |
||
Line 2: | Line 2: | ||
public class DupInt { | public class DupInt { | ||
public static void main(String[] args) { | public static void main(String[] args) { | ||
int st0 = Integer.parseInt(args[0]); // the 1st | int st0 = Integer.parseInt(args[0]); // the 1st argument on the commandline | ||
int st1 = Integer.parseInt(args[1]); // the 2nd ... | int st1 = Integer.parseInt(args[1]); // the 2nd ... | ||
int st2 = st0 + st1; | int st2 = st0 + st1; | ||
Line 9: | Line 9: | ||
} // main | } // main | ||
} // DupInt | } // DupInt | ||
Output with different arguments: | Output with different arguments: | ||
georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 4 | georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 4 | ||
Line 20: | Line 20: | ||
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 | Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 | ||
at DupInt.main(DupInt.java:3) | at DupInt.main(DupInt.java:3) | ||
<code>parseInt(String)</code> is a <code>static</code> method in the Java class <code>java.lang.Integer</code> which attempts to convert a <code>String</code> and return an <code>int</code>. It fails if the <code>String</code> does not have the proper syntax of an <code>int</code>. We will later learn how to prevent this hard failure of the program by using a <code>try { ... } catch</code> block around sensible operations. |
Latest revision as of 10:05, 24 September 2017
Complete program:
public class DupInt { public static void main(String[] args) { int st0 = Integer.parseInt(args[0]); // the 1st argument on the commandline int st1 = Integer.parseInt(args[1]); // the 2nd ... int st2 = st0 + st1; st2 = st2 + st2 + st2 + st2; System.out.println(st2); } // main } // DupInt
Output with different arguments:
georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 4 24 georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 -4 -8 georg@nunki:~/work/project/bekasi/JTC$ java DupInt 0 -1 -4 georg@nunki:~/work/project/bekasi/JTC$ java DupInt Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at DupInt.main(DupInt.java:3)
parseInt(String)
is a static
method in the Java class java.lang.Integer
which attempts to convert a String
and return an int
. It fails if the String
does not have the proper syntax of an int
. We will later learn how to prevent this hard failure of the program by using a try { ... } catch
block around sensible operations.