Java Rational Lab - java

I cant seem to figure out what's wrong with my code. I commented out the reduce() method to see if it would work with the unreduced fractions (I don't think my reduce() works) and for the first ones it does work, but when it gets to double digits and the later ones I cant figure out why it isn't working.
public class Rational implements Comparable<Rational> {
private int numerator, denominator;
public Rational() { numerator = 1; denominator = 1; }
public Rational(int num, int denom) { numerator = num; denominator = denom; }
public void setRational(int num, int denom) { setNumerator(num); setDenominator(denom); }
public void setNumerator(int num) { numerator = num; }
public void setDenominator(int denom) { denominator = denom; }
public int getNumerator() { return numerator; }
public int getDenominator() { return denominator; }
public void reduce() {
setNumerator(this.numerator / gcd(this.numerator, this.denominator));
setDenominator(this.denominator / gcd(this.numerator, this.denominator));
}
public int gcd(int num1, int num2) {
if (num2 == 0) return num1;
return gcd(num2,num1 % num2);
}
public Object clone() { return new Rational(getNumerator(), getDenominator()); }
public boolean equals(Object obj){ return this.compareTo((Rational)obj) == 0; }
public void add(Rational other) {
this.setNumerator( (this.getNumerator() * other.denominator ) + ( other.numerator * this.getDenominator() ));
this.setDenominator( this.getDenominator() * other.denominator );
//reduce();
}
public void sub(Rational other) {
numerator = ( this.getNumerator() * other.getDenominator() ) - ( other.getNumerator() * this.getDenominator() );
denominator = ( this.getDenominator() * other.getDenominator() );
//reduce();
}
public void mult(Rational other) {
numerator = ( this.getNumerator() * other.getNumerator() );
denominator = ( this.getDenominator() * other.getDenominator() );
//reduce();
}
public void div(Rational other) {
numerator = (this.getNumerator() * other.getDenominator());
denominator = (this.getDenominator() * other.getNumerator());
//reduce();
}
public int compareTo(Rational other) {
reduce();
other.reduce();
if ( this.getDenominator() < other.getDenominator() ) {
return -1;
}
else if ( this.getDenominator() == other.getDenominator() ) {
if( this.getNumerator() < other.getNumerator() ) {
return -1;
}
else if( this.getNumerator() > other.getNumerator() ) {
return 1;
}
else return 0;
}
else return 1;
}
public String toString() {
return this.numerator + "/" + this.denominator + "\n";
}
}
this is the runner
import static java.lang.System.out;
public class RationalRunner {
public static void main(String args[]) {
Rational test = new Rational();
out.println("test = " + test);
Rational newOne = new Rational(3, 4);
out.println("newOne = " + newOne);
out.println("test.equals(newOne) = " + test.equals(newOne));
newOne = (Rational) test.clone();
out.println("\n\nnewOne after test.clone() = " + newOne);
out.println("test.equals(newOne) = " + test.equals(newOne));
Rational rOne = new Rational(1, 2);
Rational rTwo = new Rational(2, 3);
out.println("1/2.equals(2/3) = " + rOne.equals(rTwo));
test.setRational(4, 6);
out.println("2/3.equals(4/6) = " + rTwo.equals(test));
out.println("\n\nrOne = " + rOne);
out.println("rTwo = " + rTwo);
out.println("rOne.compareTo(rTwo) = " + rOne.compareTo(rTwo));
out.println("rTwo.compareTo(rOne) = " + rTwo.compareTo(rOne));
rOne.add(rTwo);
out.println("\n\nrOne.add(rTwo) = " + rOne);
rOne.setRational(1, 2);
rTwo.setRational(1, 3);
rOne.add(rTwo);
out.println("\n\n1/2.add(1/3) = " + rOne);
rOne.setRational(4, 10);
rTwo.setRational(3, 5);
rOne.add(rTwo);
out.println("\n\n4/10.add(3/5) = " + rOne);
rOne.setRational(2, 10);
rTwo.setRational(3, 6);
rOne.add(rTwo);
out.println("\n\n2/10.add(3/6) = " + rOne);
//1/4 + 2/8 = 1/2
rOne.setRational(1, 4);
rTwo.setRational(2, 8);
out.println("\n\n1/4.equals(2/8) = " + rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/4.add(2/8) = " + rOne);
//1/6 + 2/8 = 5/12
rOne.setRational(1, 6);
rTwo.setRational(2, 8);
out.println("\n\n1/6.equals(2/8) = " + rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/6.add(2/8) = " + rOne);
}
}

For example, when you set one of them to 1/6 and 2/8, it comes up with 14/48 when it should be 20/48. I have tried retyping the add method and trying a different way, but it still comes out with the 14/48, im not sure why
As your example, when i comment out .equals() method, it return the correct value.
So, i check your .compareTo() method and find out, you reduce on raw data. It's means after compare, the value of rOne and rTwo was modified.
You should clone object and calculate on them
Rational num1 = new Rational(numerator, denominator);
Rational num2 = new Rational(other.getNumerator(), other.getDenominator());
I've correct them:
public int compareTo(Rational other) {
//Should create copy constructor
Rational num1 = new Rational(numerator, denominator);
Rational num2 = new Rational(other.getNumerator(), other.getDenominator());
num1.reduce();
num2.reduce();
if (num1.getDenominator() < num2.getDenominator()) {
return -1;
} else if (num1.getDenominator() == num2.getDenominator()) {
if (num1.getNumerator() < num2.getNumerator()) {
return -1;
} else if (num1.getNumerator() > num2.getNumerator()) {
return 1;
} else {
return 0;
}
} else {
return 1;
}
}
P/s: I just check with your example. So any calculator is wrong, you can correct on the same way.

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

Java : Add method Generic Class

I'm new to Java. The Following Code is to create a generic class to generate complex numbers from real and Imaginary Parts. The add() method in the class is throwing the following Error.
Not sure how to proceed further. I have been at this for a day. Error Prompt
import java.util.*;
class ComplexNum<T>{
T i;
T r;
public ComplexNum (T r , T i){
this.r = r;
this.i = i;
}
public ComplexNum add(ComplexNum c2)
{
return new ComplexNum (r + c2.r, i +c2.i);
}
#Override
public String toString() {
return this.r + " + " + this.i + "i";
}
}
class Main{
public static void main(String[] args) {
int n1 = 1;
int n2 = 3;
double d1 =4.4;
double d2 = 5.4;
ComplexNum<Integer> c1 = new ComplexNum<Integer>(n1, n2);
ComplexNum<Double> c2 = new ComplexNum<Double>(d1, d2);
ComplexNum<Double> c3 = c1.add(c2);
System.out.println(c1 + " + " + c2 + " = "+ c3) ;
}
}
static class ComplexNum<T extends Number> {
T i;
T r;
public ComplexNum(T r, T i) {
this.r = r;
this.i = i;
}
public ComplexNum<Double> add(ComplexNum c2) {
Double newr = r.doubleValue() + c2.r.doubleValue();
Double newi = i.doubleValue() + c2.i.doubleValue();
return new ComplexNum<>(newr, newi);
}
#Override
public String toString() {
return this.r + " + " + this.i + "i";
}
}
class Main {
public static void main(String[] args) {
int n1 = 1;
int n2 = 3;
double d1 = 4.4;
double d2 = 5.4;
ComplexNum<Integer> c1 = new ComplexNum<>(n1, n2);
ComplexNum<Double> c2 = new ComplexNum<>(d1, d2);
ComplexNum<Double> c3 = c1.add(c2);
System.out.println(c1 + " + " + c2 + " = " + c3);
}
}

Java not outputting or requesting keyboard input

I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.

multiple loops with only one variable

so im super stuck.. im doing my toString() method and it needs to show a bar graph with stars that correlate with the number of grades. ex.
how it should look if 5 As, 3 Bs, 3 Cs, 2 Ds, 1 F,
*****A
***B
***C
**D
*F
my teacher gave me a start, but i have no idea what to do besides concatenating the single variable thats been given. keep in mind I'm learning still and haven't learned the other ways such as string building or arrays
public class GradeDistribution {
private int mNumberAs;
private int mNumberBs;
private int mNumberCs;
private int mNumberDs;
private int mNumberFs;
public GradeDistribution(int numberOfAs, int numberOfBs,
int numberOfCs, int numberOfDs,
int numberOfFs)
{
mNumberAs = numberOfAs;
mNumberBs = numberOfBs;
mNumberCs = numberOfCs;
mNumberDs = numberOfDs;
mNumberFs = numberOfFs;
}
public GradeDistribution()
{
mNumberAs = 0;
mNumberBs = 0;
mNumberCs = 0;
mNumberDs = 0;
mNumberFs = 0;
}
public void setAllGrades(int A,int B, int C, int D, int F)
{
mNumberAs = A;
mNumberBs = B;
mNumberCs = C;
mNumberDs = D;
mNumberFs = F;
}
public void setNumberAs( int A)
{
mNumberAs = A;
}
public void setNumberBs(int B)
{
mNumberBs = B;
}
public void setNumberCs(int C)
{
mNumberCs = C;
}
public void setNumberDs(int D)
{
mNumberDs = D;
}
public void setNumberFs(int F)
{
mNumberFs = F;
}
public int getNumberOfGrades()
{
return mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
}
public int getPercentAs()
{ double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageAs = (mNumberAs / totalGrade * 100);
return (int)averageAs;
}
public int getPercentBs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageBs = (mNumberBs / totalGrade * 100);
return (int)averageBs;
}
public int getPercentCs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageCs = (mNumberCs / totalGrade * 100);
return (int) averageCs;
}
public int getPercentDs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageDs = (mNumberDs / totalGrade * 100);
return (int) averageDs;
}
public int getPercentFs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageFs = (mNumberFs / totalGrade * 100);
return (int)averageFs;
}
public String toString()
{
String output = "";
for(int a = 1; a <= mNumberAs; a++)
{
}
}
}
In your for loop you are iterating over the number of As that were given. So you can append * to your string as you iterate. output = output + "*"; When the loop is done, append an A and a new line \n, and then do the same for Bs, Cs, etc:
String output = "";
for(int a = 1; a <= mNumberAs; a++) {
output = output + "*";
}
output = output + "A\n";
// do the same for the number of Bs, Cs, etc

Overridden method from interface not found when calling

I'm trying to call a divide method that's overridden from an interface class. All similar methods (add, subtract, multiply) work just fine, except divide for some reason isn't found. Here's what I have below:
Arithmetic Interface class
public interface Arithmetic {
public Object add(Object obj);
public Object subtract(Object obj);
public Object multiply(Object obj);
public Object divide(Object obj);
}
Number class (Arithmetic methods are overridden below, divide being the last one)
public class Number implements Comparable,Arithmetic{
/**
* A string representing a non-negative number
*/
private String value;
/**
* An integer greater than or equals to 2.
*/
private int base;
/**
* - for negative numbers and otherwise null
*/
private char sign;
/**
* creates 0 base 2.
*/
public Number()
{
value = "0";
base = 2;
}
/**
* creates a number in a specified based using the specified parameters.
* #param num a string representing a non-negative number with digit
* written in uppercase letters.
* #param radix the base of the number
*/
public Number(String num, int radix) throws InvalidNumberException
{
String list = ".-0123456ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Boolean pars = false;
for (int i = 0; i < list.length(); i++) {
if (num.indexOf(list.charAt(i)) != -1) {
pars = true;
}
}
if (radix < 1 || radix > 35) {
throw new InvalidNumberException("Number invoked with a radix less than 1 or greater than 35.");
} else if ((num.indexOf(".") != num.lastIndexOf(".")) || (num.indexOf("-") != num.lastIndexOf("-"))) {
throw new InvalidNumberException("Number invoked with more than one dash or period in string.");
} else if (num.indexOf("-") != 0) {
throw new InvalidNumberException("Number invoked with dash not at beginning of string.");
} else if (num.indexOf(".") == num.length()) {
throw new InvalidNumberException("Number invoked with period at end of string.");
}
else if (pars == true) {
throw new InvalidNumberException("Number invoked with invalid character.");
}
Boolean test=false;
for (int i = 0; i < num.length(); i++) {
if ((num.charAt(i) != '-') || (num.charAt(i) != '.')) {
if (toValue(num.charAt(i)) >= radix) {
test=true;
throw new InvalidNumberException("Number invoked with digit greater or equal to radix.");
}
}
}
if(test==false){
value = num;
base = radix;
}
}
/**
* Converts a digit to its integer equivalent
* #param digit 0...9 or A...Z to be converted
* #return the integer equivalent of the specified digit.
*/
private int toValue(char digit)
{
return Character.getNumericValue(digit);
}
/**
* Converts this integer to its equivalent digit
* #param anInt an integer between 0-35
* #return the digit equivalent to an integer
*/
private char toDigit(int anInt)
{
if(anInt >= 0 && anInt <= 9)
return (char)(anInt + 48);
else if(anInt >= 10 && anInt <= 35)
return (char)(anInt + 55);
else
return (char)(-1);
}
/**
* converts a number to its decimal equivalent (double).
* #return the decimal equivalent of a number
*/
private double toDouble()
{
if (base == 10)
return Double.parseDouble(value);
int periodIndex = value.indexOf('.');
double base10Num = 0;
int i;
int radix = base;
String whole;
if (periodIndex >=0)
whole = value.substring(0, periodIndex);
else
whole = value;
int j=0;
int wholeLength = whole.length();
for (i=wholeLength-1; i>=0; i--)
base10Num = base10Num + toValue(whole.charAt(i))*(int)Math.pow(radix,wholeLength-i-1);
if (periodIndex >= 0)
{
String fract = value.substring(periodIndex+1,value.length());
int fractLength = fract.length();
for (i=0; i<fractLength; i++)
{
base10Num = base10Num + toValue(fract.charAt(i))*Math.pow(radix,-i-1);
}
}
if (sign == '-')
base10Num *= -1;
return base10Num;
}
/**
* converts a decimal number (double) to its equivalent representation
* in a given base.
* #param dec the decimal (base 10) number
* #radix the base to convert the number to.
* #return the equivalent number in the specified base
*/
private Number doubleToNumber(double dec, int radix)
{
if (radix == 10)
return new Number(Double.toString(dec),radix);
String numSign="";
if (dec < 0)
{
numSign = "-";
dec = -dec;
}
int whole = (int)dec;
double fract = dec - whole;
String numStr = "";
while (whole != 0)
{
numStr = toDigit(whole%radix) + numStr;
whole = whole / radix;
}
if (fract != 0)
{
numStr += ".";
int tolerance = 20;
int precision = 0;
while (precision < tolerance && fract != 0)
{
fract = fract * radix;
numStr += toDigit((int)(fract));
precision++;
fract = fract - (int)fract;
}
}
return new Number(numSign+numStr,radix);
}
/**
* Gives a string representation of this number in the
* format number[base].
* #return a string representation of this number
*/
#Override
public String toString()
{
return String.format("%s%s[%d]", this.sign, this.value, this.base);
}
#Override
public boolean equals(Object obj)
{
if (!(obj instanceof Number))
return false;
return (this.toDouble()==((Number)obj).toDouble());
}
#Override
public int compareTo(Object obj) throws IllegalArgumentException
{
if (!(obj instanceof Number))throw new IllegalArgumentException();
else if(this.toDouble()<((Number)obj).toDouble()) return -1;
else if(this.toDouble()>((Number)obj).toDouble()) return 1;
else return 0;
}
/**
* This method adds two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new added number object
*/
#Override
public Object add(Object obj) throws IllegalArgumentException {
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else {
return doubleToNumber((this.toDouble() + ((Number) obj).toDouble()), ((Number) obj).base);
}
}
/**
* This method subtracts two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new subtracted number object
*/
#Override
public Object subtract(Object obj) throws IllegalArgumentException {
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else {
return doubleToNumber((this.toDouble() - ((Number)obj).toDouble()), ((Number) obj).base);
}
}
/**
* This method multiplies two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new multiplied number object
*/
#Override
public Object multiply(Object obj) throws IllegalArgumentException{
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else {
return doubleToNumber(this.toDouble() * ((Number)obj).toDouble(), ((Number) obj).base);
}
}
/**
* This method divides two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new divided number object
*/
#Override
public Object divide(Object obj) throws IllegalArgumentException {
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else if (((Number) obj).toDouble() == 0) {
throw new IllegalArgumentException();
} else {
return doubleToNumber((this.toDouble() / ((Number) obj).toDouble()), ((Number) obj).base);
}
}
}
And finally my demo class, NumberDemo
public class NumberDemo
{
public static void main(String[] args)
{
Number a = new Number("12.25", 8);
Number b = new Number("13.75", 8);
System.out.println(a.toString() + " + " + b.toString() + " = " +
a.add(b));
a = new Number("ABC.75", 16);
b = new Number("18.5F", 16);
Number c = new Number("2.FB", 16);
System.out.println("(" + a.toString() + " - " + b.toString() + ") / " +
c.toString() + " = " + (a.subtract(b)).divide(c));
a = new Number("3.45", 9);
b = new Number("32.25", 9);
c = new Number("3.05", 9);
System.out.println(a.toString() + "(" + b.toString() + " + " +
c.toString() + " = " + a.multiply(b.add(c)));
a = new Number("10111.11", 2);
b = new Number("1100110.01", 2);
c = new Number("-101", 2);
System.out.println("(" + a.toString() + " - " + b.toString() + ") / " +
c.toString() + " = " + (a.subtract(b)).divide(c));
a = new Number("-5", 8);
b = new Number("5", 8);
System.out.println(a.toString() + " x " + b.toString() + " = " +
a.multiply(b));
a = new Number("-0.5", 8);
b = a;
System.out.println(a.toString() + " x " + b.toString() + " = " +
a.multiply(b));
}
}
When I call all the arithmetic methods, they appear to be called just fine, however calling divide brings me the error tooltip:
cannot find symbol
symbol: method divide(Number)
location: class Object
I can't seem to find the reason for this, can anyone spot it?
This is my first time using Stockoverflow, so please let me know if anything's apart from the format norm.

Categories