Write a Java program that inputs a list of integer values in the range of -100 t
ID: 3583932 • Letter: W
Question
Write a Java program that inputs a list of integer values in the range of -100 to 100 from the keyboard and computes the sum of the squares of the input values. This program must use exception handling to ensure that the input values are in range and are legal integers, to handle the error of the sum of the squares becoming larger than a standard Integer variable can store, and to detect end-of-file and use it to cause the output of the result. In the case of overflow of the sum, an error message must be printed and the program terminated.
Explanation / Answer
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Exception;
public class SumOfSquares
{
//main function start
public static void main(String[] args)
{
//creating arraylist named numbers to store input values
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a list of numbers between -100 to 100 ");
try
{
//checks the entered number between 100 to -100
while ((in.hasNextInt()<=100)&& (in.hasNextInt()>=-100))
{
int input = in.nextInt();
numbers.add(input);
}
}//try
catch(InputMismatchException exception)
{
//please enter a valid integer
System.out.println("This is not an integer");
}
catch(Exception e){
System.out.println("number not in the range");
}
if (numbers.size() == 0)
{
System.out.println("please enter number.");
}
else
{
int total = 0;
for (int element : numbers)
{
try{
total = total + element*element;
}//try
catch(Exception ex){
System.out.println("sum of squares of given list is out of bound");
}//catch
}
System.out.println("The SumOfSquares is: " + total);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.