In: Computer Science
Complete the program below in order to make run properly by competing validName methods and add trycatch block in the main method.
public class ExceptionWithThrow {
public static String validName(String name) throws InputMismatchException{
// check here if the name is a valid name
// through InputMismatchException if invalid //throw
// return the name if it is valid
}
public static void main(String[] args) {
// Ask the user to enter a name and their validity through validName method
// Add try and catch block around appropriate statements
}
}
In Java Please!
In Java Please!
In Java Please!
In Java Please!
In Java Please!
Program
import java.util.*;
public class ExceptionWithThrow {
public static String validName(String name) throws
InputMismatchException{
for(int i=0; i<name.length();
i++)
{
char ch =
name.charAt(i);
if(!Character.isLetter(ch) && ch!= ' ')
throw new InputMismatchException();
}
return name;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a name: ");
String name = sc.nextLine();
try{
validName(name);
}catch(InputMismatchException e){
System.out.println ("Invalid
name!");
}
}
}
Output:
Enter a name: John123
Invalid name!
Solving your question and
helping you to well understand it is my focus. So if you face any
difficulties regarding this please let me know through the
comments. I will try my best to assist you. However if you are
satisfied with the answer please don't forget to give your
feedback. Your feedback is very precious to us, so don't give
negative feedback without showing proper reason.
Always avoid copying from existing answers to avoid
plagiarism.
Thank you.