10.8k views
0 votes
There is an application which inputs hundred numbers from the user, if user enters a positive number it increments valid numbers count. But if a user enters other than integer it terminates. You are required to make changes in given code such that instead of termination it shows message “input is not valid” and re input a number. importjavax.swing.*; publicclass QuestionNumber4 { publicstaticvoidmain(String[] args) { intcountValidNumber=0; int num; for(inti=0;i 0){ countValidNumber++; } } System.out.println("Valid Numbers Are:"+countValidNumber); }

1 Answer

5 votes

Answer:

Following are the correct code to this question:

import java.util.*;//import package

public class QuestionNumber4 //defining class QuestionNumber4

{

public static void main(String[] args)//defining the main method

{

int countValidNumber=0,n=0;//defining integer varaible

int num[]= new int[100]; //defining integer array num

Scanner ob=new Scanner(System.in);//creating Scanner class Object

try //using try block

{

for(int i=0;i<100;i++)//defining loop to input 100 values

{num[i]=ob.nextInt();//input value in array

n=n+num[i];//add number

countValidNumber++;//count input value

if(n<0){}}//defining if block to check another value

}

catch(Exception e) //catch block to handle Exception

{

System.out.println("input is not valid");// print message

}

System.out.println("total intered number are: " + countValidNumber);//print times of input value

}

}

Output:

2

5

7

9

o

input is not valid

total intered nyumber are: 4

Step-by-step explanation:

following are the description of the above code:

  • In the above program code, a class "QuestionNumber4" is declared, inside the class main function is declared, in this method two integer variable "countValidNumber, n" and an integer array "num" is declared.
  • In the next step, the scanner class object is created to input the value from the user and passed into the try-catch block.
  • In the try block, we input values with the help of loop and in the catch block, we handle there exception and at the last, we print times of input, when user input numbers.
User Paul Hedderly
by
8.0k points