Language: Java Use inheritance to create a hierarchy of Exception classes -- End
ID: 3694435 • Letter: L
Question
Language: Java
Use inheritance to create a hierarchy of Exception classes -- EndOfSentenceException, PunctuationException, and CommaException. EndOfSentenceException is the parent class to PunctuationException, which is the parent class to CommaException.
Test your classes in a Driver class with a main method that asks the user to input a sentence. If the sentence ends in anything except a period (.), exclamation point (!), or question mark (?), the program should throw a PunctuationException. If the sentence specifically ends in a comma, the program should throw a CommaException. Use a catch block to catch all EndOfSentenceExceptions, causing the program to print a message and terminate. If a general PunctuationException is caught, the program should print "The sentence does not end correctly." If a CommaException is caught, the program should print "You can't end a sentence in a comma." If there are no exceptions, the program should print "The sentence ends correctly." and terminate.
Explanation / Answer
Answer for Question:
I have written this below code as specified in problem statement and i have presented this below code as of my knowledge. It may helps to you solve the given question.
import java.util.Scanner;
class EndOfSentenceException
{
void method3() throws EndOfSentenceException
{
}
}
class PunctuationException extends EndOfSentenceException
{
void method2() throws PunctuationException
{
}
}
class CommaException extends PunctuationException
{
void method() throws CommaException
{
}
}
public class DriverException
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
EndOfSentenceException obj = new EndOfInputException();
System.out.println("Enter String :");
try
{
String str = sc.next();
if(str.lastIndexOf( '.') == '.' || str.lastIndexOf( '?') == '?' || str.lastIndexOf( '.') == '!')
{
System.out.println("The sentence ends correctly.");
}
else if(str.lastIndexOf( ',') == ',')
{
obj.method();
}
else
{
obj.method2();
}
}
catch(PunctuationException e)
{
System.out.println("The sentence does not end correctly.");
}
catch(CommaException e)
{
System.out.println("You can't end a sentence in a comma.");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.