: Write a Java program that uses while loops to read an integer number between 2
ID: 3758108 • Letter: #
Question
: Write a Java program that uses while loops to read an integer number between 20 and 60, then the program prints out the entered value followed by (on a separate line) the sum of all even integer values between 2 and the entered number (including the entered value if even). Use a while loop to validate the user input before determining and printing the sum. In addition, design your program such it allows the user to re-run the program with a different input. Use proper labels for the outputs as shown in the examples below.
Entered value: 20
Sum of even numbers between 2 and 20 is: 110
Entered value: 25
Sum of even numbers between 2 and 25 is: 156
Entered value: 30
Sum of even numbers between 2 and 30 is: 240
Entered value: 40
Sum of even numbers between 2 and 40 is: 420
Entered value:
60 Sum of even numbers between 2 and 60 is: 930
Explanation / Answer
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Numbers
{
public static int sum(int n)
{
int sum = 0;
for(int i=2;i<=n;i++)
if(i%2==0)
sum = sum+i;
return sum;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner input = new Scanner(System.in);
int number;
while(true)
{
System.out.println("Input an integer in between 20 and 60 : ");
number = input.nextInt();
if(number>=20 && number<=60)
{
System.out.println("Entered value : "+number);
System.out.println("Sum of even numbers between 2 and "+number+" is : "+sum(number));
}
else
{
System.out.println("Number should be in specified range. Enter the number again.");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.