Java Tutorial
Reads command line integer arguments and computes the sum of them.
To convert string to integer, Integer.parseInt method is used here.
class SumTest { public static void main(String[] values) { int sum = 0; System.out.println("Calculates Sum for below Integers"); for(int i=0;i<values.length;i++){ System.out.println(values[i]); sum = sum + Integer.parseInt(values[i]); } System.out.println("Sum :" + sum); } }Output:
D:\Java_Programs>javac SumTest.java D:\Java_Programs>java SumTest 10 20 30 40 50 Calculates Sum for below Integers 10 20 30 40 50 Sum :150
Need to use run configurations option to provide command line arguments if we are using Eclipse SDK for java application development.
Go to run menu, click run configurations and select Arguments tab to provide arguments like below.
Once provided the command line arguments, click on run option to see the result of the java program in Eclipse SDK.
If we pass invalid integer value as command line arguments, above java program fails to calculate the sum and throws exception.
D:\Java_Programs>javac SumTest.java D:\Java_Programs>java SumTest 10 20 30 40 50 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 sum for remaining valid command line integer arguments.
class SumTest { public static void main(String[] values) { int sum = 0; System.out.println("Calculates Sum for below Integers"); for(int i=0;i<values.length;i++){ System.out.println(values[i]); try { sum = sum + Integer.parseInt(values[i]); } catch (NumberFormatException e) { System.out.println("Invalid integer command line arguments: " + e.toString()); } } System.out.println("Sum :" + sum); } }Output:
D:\Java_Programs>javac SumTest.java D:\Java_Programs>java SumTest 10 20 30 40 50 Test Calculates Sum for below Integers 10 20 30 40 50 Test Invalid integer command line arguments: java.lang.NumberFormatException: For input string: "Test" Sum :150
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page