My question is how can I create-a try method to read the strings from the user until
Fantastic news! We've Found the answer you've been seeking!
Question:
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."); } }
Posted Date: