Create a Project with the name Chap12. Create a Class with the name StringTooLon
ID: 3837755 • Letter: C
Question
Create a Project with the name Chap12. Create a Class with the name StringTooLongException This throws an exception when a string is discovered that has more than 20 characters in it. Create a driver Class with the name ReadStrings This reads a string from the user until the user enters "DONE". If a string is entered that has more than 20 characters, throw an exception. The program should catch and handle the exception if it is thrown. Handle the exception by printing an appropriate message, and then continue processing more strings. See page 642, 643 for reference. Zip the folder Chap12 and upload the file Output: Enter strings, enter DONE when finished: this is a long string String has too many characters Please: OK. a short string You entered: OK. a short string Done You entered: DoneExplanation / Answer
import java.util.Scanner;
public class ReadStrings {
public static void main(String args[]) {
System.out.println("Enter a string (or DONE to exit) : ");
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
while ( !inputString.equalsIgnoreCase("DONE") ) {
try {
/*
* Throw the exception if there are more than 20 characters
*/
if (inputString.length() > 20) {
throw new StringTooLongException("String has too many characters");
}
System.out.println("You entered : " + inputString);
} catch (StringTooLongException e) {
System.out.println(e);
System.out.println("Please try again : ");
}
System.out.println("Enter a string (or DONE to exit) : ");
inputString = sc.nextLine();
}
sc.close();
}
}
------------------------------------------------------------------------------------------------------------------------------
public class StringTooLongException extends Exception {
private static final long serialVersionUID = 6022793823280769846L;
private String message;
public StringTooLongException(String message) {
this.message = message;
}
public String toString() {
return "StringTooLongException - [message = " + message + "]";
}
}