NPTEL Programming in Java Week 5 Programming Assignment 4 Solution

 In the following program, an array of integer data to be initialized. During the initialization, if a user enters a value other than integer value, then it will throw InputMismatchException exception. On the occurrence of such an exception, your program should print “You entered bad data.” If there is no such exception it will print the total sum of the array.

Select the Language for this assignment. 
File name for this program : 
1
//Prefixed Fixed Code:
2
import java.util.*;
3
public class Question5_4{
4
  public static void main(String[] args) {
5
      Scanner sc = new Scanner(System.in); 
6
      int length = sc.nextInt(); 
7
      // create an array to save user input 
8
      int[] name = new int[length];
9
      int sum=0;//save the total sum of the array.
10
//Define try-catch block to save user input in the array "name", if there is an exception then catch the exception otherwise print the total sum of the array.
11
for(int i=0 ; i<length ; i++)
12
        {
13
          try{
14
             name[i] = sc.nextInt();
15
             sum += name[i];
16
          }catch(InputMismatchException e){
17
              sum = -1;
18
          }
19
      }
20
          if(sum == -1)
21
              {
22
                   System.out.print("You entered bad data.");
23
              }
24
          else
25
              {
26
                  System.out.print(sum);
27
              }
0
}
1
}
Post a Comment (0)
Previous Question Next Question

You might like