In: Computer Science
Write a Java program which reads a positive integer from the command line, then displays the sum of all even values up to and including the value provided, followed by the sum of all odd values up to and including the value provided.
Expected console output follows. Command line argument shown in red. Output was generated by multiple runs of the program to test input validation.
D:\COP2800C> java Sums 0
Value entered is 0
0 is out of range.
D:\COP2800C> java Sums -1
Value entered is -1
-1 is out of range.
D:\COP2800C> java Sums 5.5
Value entered is 5.5
5.5 is not an integer.
D:\COP2800C> java Sums hello
Value entered is hello
hello is not an integer.
D:\COP2800C> java Sums 5
Value entered is 5
The sum of the even numbers up to 5 is 6
The sum of the odd numbers up to 5 is 9
Hi,
Please find the answer below:
----------------------------------------------------
Java code:
import java.util.Scanner;
//Sums.java
public class Sums {
public static void main(String[] args) {
//variables to hold evens and odd
sums
int sumOfOdds=0;
int sumOfEvens=0;
try {
//parse the
command line argument
int number =
Integer.parseInt(args[0]);
System.out.println("Value entered is "+number);
if(number >
0) {
//for loop to calculate
for(int i=1;i<=number;i++) {
if(i%2 ==0)
sumOfEvens=sumOfEvens+i;
else
sumOfOdds=sumOfOdds+i;
}
//print the sums
System.out.println("The sum of the even numbers
up to " + number + " is " + sumOfEvens);
System.out.println("The sum of the odd numbers
up to " + number + " is " + sumOfOdds);
}else {
System.out.println(number + " is out of
range.");
}
//
catch exception
}catch(NumberFormatException nfe)
{
System.out.println(args[0] + " is not an integer.");
}
}
}
Sample output:
Value entered is 5
The sum of the even numbers up to 5 is 6
The sum of the odd numbers up to 5 is 9
Screenshot:
-----------------------------------------------------
Hope this helps.
Kindly like the solution if it is useful to you.
Let me know if you need more help.
Thanks.