Answered step by step
Verified Expert Solution
Question
1 Approved Answer
My question is how can I create-a try method to read the strings from the user until they enter 'DONE'. If the string has more
My question is how can I create-a try method to read the strings from the user until they enter 'DONE'.
If the string has more than 35 characters the program will throw it to my StringTooLongException class printing the sentence "string is too long" then continuing back to asking the user to enter a string.
Example Output:
Enter a string: Peter Piper picked a peck of pickled peppers This string is too long. Enter a string: Sheena leads, Sheila needs Enter a string: Seventy seven benevolent elephants Enter a string: How can a clam cram in a clean cream can? This string is too long. Enter a string: DONE
Here is my current code that I have.
//Accepts user input import java.util.Scanner; public class driver2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a string:"); String ss = scanner.nextLine(); // method to check our string and its length try { checkString(ss); } //Catch exception and list exception catch(Exception e) { System.out.println("A problem occured: " + e); } } //If string is over 35 characters, we will throw to a new StringTooLongException static void checkString(String ss) throws StringTooLongException{ if(ss.length()<35) { throw new StringTooLongException("Enter a string:"); } } } // custom StringTooLongException class to be thrown back // when the string user has entered is more than 35 characters class StringTooLongException extends Exception{ public StringTooLongException() { super("This string is too long."); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started