Question

In: Computer Science

I'm having trouble with my ZeroDenominatorException. How do I implement it to where if the denominator...

I'm having trouble with my ZeroDenominatorException. How do I implement it to where if the denominator is 0 it throws the ZeroDenominatorException and the catch catches to guarantee that the denominator is never 0.
/**
 * The main class is the driver for my Rational project.
 */
public class Main {

    /**
     * Main method is the entry point to my code.
     * @param args The command line arguments.
     */
    public static void main(String[] args) {

        int numerator, denominator = 0;

        System.out.println();

        try {

            Rational rad = new Rational(-1, 3);

            if (denominator == 0)
                throw new ZeroDenominatorException();

            else {
                System.out.println(rad);
            }
        }

        catch(ZeroDenominatorException e){

            System.err.println(e.getMessage());
        }
    }
}
import java.util.Objects;

public class Rational {

    private int numerator;
    private int denominator;

    public Rational(int numerator, int denominator) {
        this.numerator = numerator;
        this.denominator = denominator;
    }

    public int getNumerator() {
        return numerator;
    }

    public void setNumerator(int numerator) {
        this.numerator = numerator;
    }

    public int getDenominator() {
        return denominator;
    }

    public void setDenominator(int denominator) {
        this.denominator = denominator;
    }

    @Override
    public String toString() {
        boolean negative = (numerator < 0 || denominator < 0) && (numerator >= 0 || denominator > 0);
        int num = numerator, denum = denominator;
        if (num < 0)
            num = -num;
        if (denum < 0)
            denum = -denum;
        if (negative)
            return "-" + num + "/" + denum;
        else
            return num + "/" + denum;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Rational rational = (Rational) o;
        return numerator == rational.numerator &&
                denominator == rational.denominator;
    }

    @Override
    public int hashCode() {
        return Objects.hash(numerator, denominator);
    }
}
public class ZeroDenominatorException extends Exception {

    public ZeroDenominatorException(){

        super("The denominator cannot be zero!");
    }
}

Solutions

Expert Solution

/**
* The main class is the driver for my Rational project.
*/
public class Main {

/**
* Main method is the entry point to my code.
* @param args The command line arguments.
*/
public static void main(String[] args) {

int numerator=5;
int denominator = 0;
System.out.println();
try {
   Rational rad = new Rational(numerator,denominator);
   System.out.println(rad);
}
catch(ZeroDenominatorException e){

System.err.println(e.getMessage());
}
}
}

import java.util.Objects;

public class Rational {

private int numerator;
private int denominator;

public Rational(int numerator, int denominator) throws ZeroDenominatorException {
this.numerator = numerator;
this.setDenominator(denominator);
}

public int getNumerator() {
return numerator;
}

public void setNumerator(int numerator) {
this.numerator = numerator;
}

public int getDenominator() {
return denominator;
}

public void setDenominator(int denominator) throws ZeroDenominatorException {
   if(denominator==0){
       throw new ZeroDenominatorException();
   }
   else{
this.denominator = denominator;
   }
}

@Override
public String toString() {
boolean negative = (numerator < 0 || denominator < 0) && (numerator >= 0 || denominator > 0);
int num = numerator, denum = denominator;
if (num < 0)
num = -num;
if (denum < 0)
denum = -denum;
if (negative)
return "-" + num + "/" + denum;
else
return num + "/" + denum;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Rational rational = (Rational) o;
return numerator == rational.numerator &&
denominator == rational.denominator;
}

@Override
public int hashCode() {
return Objects.hash(numerator, denominator);
}
}

public class ZeroDenominatorException extends Exception {

public ZeroDenominatorException(){

super("The denominator cannot be zero!");
}
}

Expected output:

when numerator=5 and denominator =0

The denominator cannot be zero!

when numerator=5 and denominator=2

5/2


Related Solutions

I'm having trouble with my do while loop. I'm trying to get it where if the...
I'm having trouble with my do while loop. I'm trying to get it where if the user enter's 3 after whatever amount of caffeinated beverages they've entered before then the loop will close and the rest of my code would proceed to execute and calculate the average price of all the caffeinated beverages entered. Can someone please help me with this? Here's my Code: import java.util.Scanner; public class Main { public static void main(String[] args) { CaffeinatedBeverage[] inventory = new...
I'm having trouble with validating this html code. Whenever I used my validator, it says I...
I'm having trouble with validating this html code. Whenever I used my validator, it says I have a stray end tag: (tbody) from line 122 to 123. It's the last few lines. Thanks and Ill thumbs up whoever can help solve my problem. Here's my code: <!DOCTYPE html> <html lang="en"> <head> <title>L7 Temperatures Fields</title> <!--    Name:    BlackBoard Username:    Filename: (items left blank for bb reasons    Class Section: (blank)    Purpose: Making a table to demonstrate my...
Hello, I am having trouble getting started on my project and building these functions. How do...
Hello, I am having trouble getting started on my project and building these functions. How do I build a function that continuously adds new "slices" to the list if they are below/above the size limit? I didn't copy the entire problem, but just for reference, when the code is run it will take user input for size limit (L), time cost for a random slice(R), and time cost for an accurate slice(A). Question: In real life, a steak is a...
I am having trouble with a C++ code that I'm working on. It is a spell...
I am having trouble with a C++ code that I'm working on. It is a spell checker program. It needs to compare two arrays, a dictionary, and an array with misspelled strings that are compared to the strings in the dictionary. the strings that are in the second array that is not in the Dictionary are assumed to be misspelled. All of the strings in the dictionary are lowercase without any extra characters so the strings that are passed into...
I'm having trouble understanding a CS assignment. I would appreciate it if you all code do...
I'm having trouble understanding a CS assignment. I would appreciate it if you all code do this for me. The template for the lab is below which you must use. You're only supposed to create/edit the product function. The assignment has to be written in asm(Mips) You will need to create a NOS table and use the structure below and write a function called product. The structure used in this program is: struct Values { short left; short right; int...
I'm having trouble trying to create the italian, polish, and netherlands flag in C Here's my...
I'm having trouble trying to create the italian, polish, and netherlands flag in C Here's my code so far: #include<stdio.h> int main(){    int country_choice;    fprintf(stderr, "Enter the country_code of the chosen flag.(1 for Poland, 2 for Netherlands, 3 for Italy)");    fscanf(stdin, "%d", &country_choice);    switch (country_choice) { case 1: printf("Poland Flag\n"); printf("%c%c%c", 255,255,255); printf("%c%c%c", 220,20,60);    break;       case 2: printf("Italian Flag\n"); printf("%c%c%c", 0,146,70); printf("%c%c%c", 225,255,255); printf("%c%c%c", 206,43,55); break;    case 3: printf("Netherlands Flag\n"); printf("%c%c%c", 174,28,40);...
Using dev c++ I'm having trouble with classes. I think the part that I am not...
Using dev c++ I'm having trouble with classes. I think the part that I am not understanding is sending data between files and also using bool data. I've been working on this program for a long time with many errors but now I've thrown in my hat to ask for outside help. Here is the homework that has given me so many issues: The [REDACTED] Phone Store needs a program to compute phone charges for some phones sold in the...
I'm having trouble figuring out the constraints to this problem. I know that I am maximizing...
I'm having trouble figuring out the constraints to this problem. I know that I am maximizing 55x + 45y, however the variables are throwing me off. I only need help on question #1 as it would be a great help to understanding the rest of what the questions are asking. The problem is as follows: NorCal Outfitters manufactures a variety of specialty gear for outdoor enthusiasts. NorCal has decided to begin production on two new models of crampons: the Denali...
hello, I'm having trouble understanding how to do these two problems could you show me a...
hello, I'm having trouble understanding how to do these two problems could you show me a step by step. 1)Eight sprinters have made it to the Olympic finals in the 100-meter race. In how many different ways can the gold, silver, and bronze medals be awarded? 2)Suppose that 34% of people own dogs. If you pick two people at random, what is the probability that they both own a dog? Give your answer as a decimal (to at least 3...
Hey! I'm having trouble answering this for my assignment. Thank you so much in advance. 1)...
Hey! I'm having trouble answering this for my assignment. Thank you so much in advance. 1) Which type of vessels, arteries or veins, has more muscle fibers? What is the functional significance of this? 2a) In general, we have no conscious control over smooth muscle or cardiac muscle function, whereas we can consciously control to some extent all skeletal muscles. Can you consciously control your breathing? What does this tell you about the muscle type of the diaphragm? 2b) What...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT