Question

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 …
      1. When the argument passed to the constructor is null.
      2. When any of the following applies to the String argument that is passed to the constructor …
        • this String does not contain exactly one '/' character
        • not all characters of this String ( other than the one '/' ) are decimal digits
        • within this String, there is not at least one decimal digit preceding the '/' character
        • within this String, there is not at least one decimal digit following the '/' character

I am having issues with getting the MalformedRationalException to throw different messages any of the four examples errors are submitted in the command line

------------------------------------------------------------------------------------------------------------------------------------------------------

public class Main
{
public static void main ( String[] args )
{
System.out.println ( "args[0] is ........ \"" + args[0] + "\"" ) ;
try
{
Rational r = new Rational ( args[0] ) ;
System.out.println ( "A Rational object was successfully constructed from \"" + args[0] +"\"." ) ;
System.out.println ( "Numerator is ...... " + r.numerator() ) ;
System.out.println ( "Denominator is .... " + r.denominator() ) ;
} // try
catch ( MalformedRationalException mre )
{
System.out.println ( "A Rational object could not be constructed from \"" + args[0] +"\"." ) ;
System.out.println ( mre.getMessage() ) ;
} // catch
} // main
} // Main

-------------------------------------------------------------------------------------------------------------------------------------------------

public class MalformedRationalException extends Exception
{
public MalformedRationalException ( String message )
{ super ( message ) ; }
} // MalformedRationalException

---------------------------------------------------------------------------------------------------------------------------------------------------

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

Please find the answer below, I have created the constructor with the messages provided in the question. You can change them according to our needs. I have mentioned all the details in the comments.

Rational.java
public class Rational {
    //private members of the class
    private int numerator;
    private int denominator;

    //public methods to get the values
    public int numerator(){
        return numerator;
    }
    public int denominator(){
        return denominator;
    }

    //constructor
    Rational(String value) throws MalformedRationalException {
        //first check if the value is null or string is empty
        if(value == null || value.isEmpty()){
            throw new MalformedRationalException("String passed is NULL");
        }
        //check for the index of "/", it should present
        //check for single "/" is using the comparison of first and last occurrence of the "/"
        else if(value.indexOf("/") == -1 || value.indexOf("/")!=value.lastIndexOf("/")){
            throw new MalformedRationalException("String Does not contain exactly one '/' character");
        }
        else{
            //get the index of "/"
            int slashIndex = value.indexOf("/");
            //check for the only digits in the string
            for (int i = 0; i < value.length(); i++) {
                if(i!= slashIndex) {
                    if (!Character.isDigit(value.charAt(i))) {
                        throw new MalformedRationalException("Not all characters of this String ( other than the one '/' ) are decimal digits");
                    }
                }
            }
            //check for the digits before and after "/"
            boolean before = false;
            boolean after = false;
            //first check for the digit before the "/"
            for (int i = 0; i < slashIndex ; i++) {
                if(Character.isDigit(value.charAt(i))){
                    before = true;
                }
            }
            //first check for the digits after the "/"
            for (int i = slashIndex+1; i < value.length() ; i++) {
                if(Character.isDigit(value.charAt(i))){
                    after = true;
                }
            }

            //throw errors accordingly
            if(!before){
                throw new MalformedRationalException("There is not at least one decimal digit preceding the '/' character");
            }

            if(!after){
                throw new MalformedRationalException("There is not at least one decimal digit following the '/' character");
            }
        }

        //if everything is good then assign the values accordingly
        int slashIndex = value.indexOf("/");
        numerator = Integer.parseInt(value.substring(0,slashIndex));
        denominator = Integer.parseInt(value.substring(slashIndex+1));
    }
}
MalformedRationalException.java
public class MalformedRationalException extends Exception {
    public MalformedRationalException(String message){
        super(message);
    }
}
Main.java
public class Main {
    public static void main ( String[] args )
    {
        System.out.println ( "args[0] is ........ \"" + args[0] + "\"" ) ;
        try
        {
            Rational r = new Rational (args[0]) ;
            System.out.println ( "A Rational object was successfully constructed from \"" + args[0] +"\"." ) ;
            System.out.println ( "Numerator is ...... " + r.numerator() ) ;
            System.out.println ( "Denominator is .... " + r.denominator() ) ;
        } // try
        catch ( MalformedRationalException mre )
        {
            System.out.println ( "A Rational object could not be constructed from \"" + args[0] +"\"." ) ;
            System.out.println ( mre.getMessage() ) ;
        } // catch
    } // main
}

Output:

Legal input:

Input: 1212

Input: 12//12

Input: /12

Input: 12/

Add a comment
Know the answer?
Add Answer to:
given the following two classes Within a file named Rational.java, define a public class named Rational...
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
  • Rational will be our parent class that I included to this post, Implement a sub-class MixedRational....

    Rational will be our parent class that I included to this post, Implement a sub-class MixedRational. This class should Implement not limited to: 1) a Constructor with a mathematically proper whole, numerator and denominator values as parameters. 2) You will override the: toString, add, subtract, multiply, and divide methods. You may need to implement some additional methods, enabling utilization of methods from rational. I have included a MixedRational class with the method headers that I used to meet these expectations....

  • Header file for the Rational class: #ifndef RATIONAL_H #define RATIONAL_H class Rational { public: Rational( int...

    Header file for the Rational class: #ifndef RATIONAL_H #define RATIONAL_H class Rational { public: Rational( int = 0, int = 1 ); // default constructor Rational addition( const Rational & ) const; // function addition Rational subtraction( const Rational & ) const; // function subtraction Rational multiplication( const Rational & ) const; // function multi. Rational division( const Rational & ) const; // function division void printRational () const; // print rational format void printRationalAsDouble() const; // print rational as...

  • File Factorials.java contains a program that calls the factorial method of the MathUtils class to compute...

    File Factorials.java contains a program that calls the factorial method of the MathUtils class to compute the factorials of integers entered by the user. In this program, two things can possibly occur: The program always returns 1 if negative integers are entered by the user. Returning 1 as the factorial of any negative integer is not correct. The program also returns negative numbers when the user enters integers greater than 16. Returning a negative number for values over 16 also...

  • Problem 2 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create...

    Problem 2 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create a Java class named Complement with the following: • A public static method named onesComplement that takes a String as a parameter and returns a String that is the 1’s complement of the parameter. • If the String is not a valid binary number (i.e. only has 0s and 1s), you should throw an IllegalArgumentException with the message "Not a valid binary number". •...

  • Make a new class called Rational to represent rational numbers in C++ language. Use a long...

    Make a new class called Rational to represent rational numbers in C++ language. Use a long to store each part (numerator and denominator). Be sure your main function fully test the class. 1. Create a helper function called gcd to calculate the greatest common divisor for the two given parameters. See Euclid’s algorithm (use google.com). Use this function to always store rationals in “lowest terms”. 2. Create a default, one argument and two argument constructor. For the two argument constructor,...

  • public class Rational { // PUT PRIVATE DATA FIELDS HERE /** * The default constructor for...

    public class Rational { // PUT PRIVATE DATA FIELDS HERE /** * The default constructor for objects of class Rational. Creates the rational number 1. */ public Rational() { // ADD CODE TO THE CONSTRUCTOR } /** * The alternate constructor for objects of class Rational. Creates a rational number equivalent to n/d. * @param n The numerator of the rational number. * @param d The denominator of the rational number. */ public Rational(int n, int d) { // ADD...

  • Please write in dr java Here is the driver: import java.util.*; public class SquareDriver { public...

    Please write in dr java Here is the driver: import java.util.*; public class SquareDriver { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String input =""; System.out.println("Welcome to the easy square program"); while(true) { System.out.println("Enter the length of the side of a square or enter QUIT to quit"); try { input = keyboard.nextLine(); if(input.equalsIgnoreCase("quit")) break; int length = Integer.parseInt(input); Square s = new Square(); s.setLength(length); s.draw(); System.out.println("The area is "+s.getArea()); System.out.println("The perimeter is "+s.getPerimeter()); } catch(DimensionException e)...

  • (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to...

    (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class- the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to h and would be stored in the object as 1 in the numerator...

  • Define a class for rational numbers. A rational number is a "ratio-nal" number, composed of two...

    Define a class for rational numbers. A rational number is a "ratio-nal" number, composed of two integers with division indicated. Requirement: - two member variables: (int) numerator and (int) denominator. - two constructors: one that takes in both numerator and denominator to construct a rational number, and one that takes in only numerator and initialize the denominator as 1. - accessor/modifier - member functions: add(), sub(), mul(), div(), and less(). Usage: to add rational num b and rational num a,...

  • Error: Main method not found in class ServiceProvider, please define the main method as: public static...

    Error: Main method not found in class ServiceProvider, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application This is the error im getting while executing the following code Can you modify the error import java.net.*; import java.io.*; public class ServiceProvider extends Thread { //initialize socket and input stream private Socket socket = null; private ServerSocket server = null; private DataInputStream in = null; private DataOutputStream out = null; private int...

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