Question

Complete the program below in order to make run properly by competing validName methods and add...

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

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The answer has been given below:-

import java.io.*;
import java.util.*;

public class ExceptionWithThrow
{
    public static String validName(String name)throws InputMismatchException
    {
       if ((name != null) 
                && (!name.equals("")) 
                && (name.matches("^[a-zA-Z]*$")))
            return name;
        else
            throw new InputMismatchException("Name must only contains A-Z and a-z ");
    }

        public static void main(String[] args) {
                
                Scanner sc = new Scanner(System.in);
                try {
                    System.out.println("Enter a name");
                    String name=sc.nextLine();
                    String a=validName(name);
                    System.out.println("Your name is correct..");
                    
                    } catch(InputMismatchException e) {
                        System.out.println(e);
                }
        }
}

The program will read a String name, and will throw the exception if the name contains any other character other than "A-Z" or "a-z".

I hope the program helps you. Please give a positive rating if the answer helps you. Feel free to ask for any doubts in the comments section. Happy Chegging and Happy Coding

Add a comment
Know the answer?
Add Answer to:
Complete the program below in order to make run properly by competing validName methods and add...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program...

    Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program named GetIDAndAge that continually prompts the user for an ID number and an age until a terminal 0 is entered for both. If the ID and age are both valid, display the message ID and Age OK. Throw a DataEntryException if the ID is not in the range of valid ID numbers (0 through 999), or if the age is not in the range...

  • Please provide the full code...the skeleton is down below: Note: Each file must contain an int...

    Please provide the full code...the skeleton is down below: Note: Each file must contain an int at the beginning, stating the number of records in the file. Afterwards, the number of records in the file will follow. Each record that follows will consist of a last name (String), and a gpa (double). However, to test the error handling of your program, the number of records will not always match the int value. All possible combinations should be tested. 1.) Prompt...

  • IT Java code In Lab 8, we are going to re-write Lab 3 and add code...

    IT Java code In Lab 8, we are going to re-write Lab 3 and add code to validate user input. The Body Mass Index (BMI) is a calculation used to categorize whether a person’s weight is at a healthy level for a given height. The formula is as follows:                 bmi = kilograms / (meters2)                 where kilograms = person’s weight in kilograms, meters = person’s height in meters BMI is then categorized as follows: Classification BMI Range Underweight Less...

  • Question 1 (5 points) Question 1 Unsaved What is displayed on the console when running the...

    Question 1 (5 points) Question 1 Unsaved What is displayed on the console when running the following program? public class Quiz2B { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } } } Question 1 options: The program displays Welcome to Java two times. The program displays Welcome to...

  • What is wrong with this code? Please bold the changes that were made so this code...

    What is wrong with this code? Please bold the changes that were made so this code runs properly. The Problem is: 11.16 (Catching Exceptions with SuperClasses) Use inheritance to create an exception superclass (called Exception) and exception subclasses ExceptionB and ExceptionC, where ExceptionB inherites from ExceptionA and ExceptionC inherits from ExeptionB. Write a program to demonstrate that the catch block for type ExceptionA catches exceptions of types ExceptionB and ExceptionC. I got this far but I'm still getting a lot...

  • The Calculator Class Create an application dlass called Colcustor with the following members Methods Retuns firtNumber...

    The Calculator Class Create an application dlass called Colcustor with the following members Methods Retuns firtNumber secondumber static void mainsering Asks for two integer undan uiet", ..",ЛТеп shows the result according to Note Use the attached example program and add required methods. Then une a switch tructure in the try black to call proper method according to the input operator Sample Output 1 : 2074 Sample Output 2 D1VLdeBy LerOWLthEkceptionHahaling-Jav / Handling ArithmeticExceptions and InputMismatchExceptions. import java.util.InputMismatchException; import java.util.Scanner; public...

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

  • When I try running this code in java, it doesn't work properly. The part where it...

    When I try running this code in java, it doesn't work properly. The part where it should ask the user to write some string, where I would write in "one two three four" doesn't work, it says "bash: one: command not found" Please help fix. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); System.out.println("The arguments are:"); for(String element : args) {    System.out.println("\t" + element); } } } Sample output: Hello World! The arguments are:        ...

  • given the following two classes Within a file named Rational.java, define a public class named Rational...

    given the following two classes Within a file named Rational.java, define a public class named Rational such that … the Rational class has two private instance variables, numerator and denominator, both of type int the Rational class defines two public accessor methods, numerator() and denominator() the Rational class defines a constructor that has one String parameter a throws clause indicates that this constructor could potentially throw a MalformedRationalException this constructor throws a MalformedRationalException in the following circumstances … When the...

  • Modify the objectstudent JAVA program to add a private variable zipcode, you must also add setters...

    Modify the objectstudent JAVA program to add a private variable zipcode, you must also add setters and getter methods for the new variable and modify the toString method. The objectstudent program is in this weeks module, you can give it a default value of 19090. class Student { private int id; private String name; public Student() { id = 8; name = "John"; } public int getid() { return id; } public String getname() { return name; } public void...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT