In: Computer Science
Create a method that returns the third character from the String word. Be sure to use a try catch block and use the appropriate exception to deal with indexes out of a String’s bound: StringIndexOutOfBoundsException. Return the character 'x' (lowercase) when this exception is caught. Do not use if statements and do not use the general exception handler Exception.
Examples:
thirdLetter("test") -> 's' public char thirdLetter(String word)
{
}
should return the char 'r'
Coding
import java.util.Scanner; //it is for user input
public class Simple
{
public static char thirdLetter(String words)//our static function
which will get array string from main method
{
try//try catch block if any error will come it will redirect to
catch
{
return(words.charAt(2));
}
catch(StringIndexOutOfBoundsException siobe)
{
System.out.println("invalid input No characher on third
position");//output message if
return (' ');//it will return null value in that case
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter the String
::");//output message for print
String word = sc.nextLine();//get string value from
word
System.out.println("Third Letter is
::"+thirdLetter(word));//here third letter
}
}
output:
if you still have any Problem regarding this question please comment and if you like my code please appreciate me by thumbs up thank you.........