The 'parseInt' method of the 'Integer' class throws a 'NumberFormatException' when it is passed a String argument that it cannot convert to an int. Given the String variable s (which has already been assigned a value), write the code needed to convert the value in s assigning the result to the integer variable i If a NumberFormatException is thrown, i should be assigned the value -1.

Respuesta :

Answer:

Following are the code in the java language  

try // try block

{

i = Integer.parseInt(s); // converting into the integer  

}  

catch (NumberFormatException e) // catch block

{

i = -1; // initialized i to -1.

}

Explanation:

Following is the description of code.

  • Create a try block in that clock we convert the variable "s" into the integer by using the function  Integer.parseInt and storing in the variable "i".
  • if try block gives an error the console is directly going  in the second we create a catch block for that try block In this block we initialized the variable  i to -1.