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...

  • 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,...

  • 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...

  • 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...

  • 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...

  • Adapt your Rational class : public class Rational { private int num; private int denom; public...

    Adapt your Rational class : public class Rational { private int num; private int denom; public Rational() { num = 0; denom = 1; } public Rational(int num, int denom) { this.num = num; this.denom = denom; } int getNum() { return num; } int getDenom() { return denom; } public Rational add(Rational rhs) { return new Rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom); } public Rational subtract(Rational rhs) { return new Rational(num * rhs.denom - rhs.num...

  • 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,...

  • Define a class for rational numbers. A rational number is a number that can be represented...

    Define a class for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, 1/2, 3/4, 64/2, and so forth are all rational numbers. (By 1/2 etc we mean the everyday meaning of the fraction, not the integer division this expression would produce in a C++ program). Represent rational numbers as two values of type int, one for the numerator and one for the denominator. Call the class rational Num...

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