Java Tutorial
Reads command line integer arguments and computes the multiplication of them.
To convert string to integer, Integer.parseInt method is used here.
class MultiplicationTest { public static void main(String[] values) { int product = 1; System.out.println("Calculates Multiplication for below Integers"); for(int i=0;i<values.length;i++){ System.out.println(values[i]); product = product * Integer.parseInt(values[i]); } System.out.println("Multiplication :" + product); } }Output:
D:\Java_Programs>javac MultiplicationTest.java D:\Java_Programs>java MultiplicationTest 2 3 4 5 6 Calculates Multiplication for below Integers 2 3 4 5 6 Multiplication :720
If we pass invalid integer value as command line arguments, above java program fails to calculate the multiplication and throws exception.
D:\Java_Programs>javac MultiplicationTest .java D:\Java_Programs>java MultiplicationTest 2 3 4 5 6 Test Exception in thread "main" Test java.lang.NumberFormatException: For input string: "Test" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at SumTest.main(SumTest.java:7)
try catch block is used to find the invalid command line integer arguments and finds the multiplication for remaining valid command line integer arguments.
class MultiplicationTest { public static void main(String[] values) { int product = 1; System.out.println("Calculates Multiplication for below Integers"); for(int i=0;i<values.length;i++){ System.out.println(values[i]); try { product = product * Integer.parseInt(values[i]); } catch (NumberFormatException e) { System.out.println("Invalid integer command line arguments: " + e.toString()); } } System.out.println("Multiplication :" + product); } }Output:
D:\Java_Programs>javac MultiplicationTest.java D:\Java_Programs>java MultiplicationTest 2 3 4 5 6 Test Calculates Multiplication for below Integers 2 3 4 5 6 Test Invalid integer command line arguments: java.lang.NumberFormatException: For input string: "Test" Multiplication :720
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page