You are to design a Java application to carry out additions and subtractions for
ID: 3549088 • Letter: Y
Question
You are to design a Java application to carry out additions and subtractions for numbers of any length. A number is represented as an object which includes a sign and two strings for the whole and decimal parts of the number. And, the operations must be done by adding or subtracting characters directly. You are not allowed to convert these strings to numbers before the operation.
The program must use a "Number" class which includes at least the following methods:
Number ( );
Number (double n);
Number add (Number RHS);
Number subtract (Number RHS);
String toString ( );
If anyone can do this program and explain to me the steps thoroughly, I will reward maximum points.
Explanation / Answer
package com.chegg;public class Number {
String sign;
String wholeNum;
String decimal;
Number(){
}
Number(double n){
if(n>0)
this.sign="+";
else if(n<0)
this.sign="";
this.wholeNum = String.valueOf((int)(n));
String num = String.valueOf(n);
this.decimal = num.substring(num.indexOf("."));
}
Number add(Number RHS){
double rhs = Double.parseDouble(RHS.toString());
double orignalNum = Double.parseDouble(this.toString());
double sum = orignalNum+rhs;
return new Number(sum);
}
Number subtract(Number RHS){
double rhs = Double.parseDouble(RHS.toString());
double orignalNum = Double.parseDouble(this.toString());
double difference = orignalNum-rhs;
return new Number(difference);
}
public String toString(){
return this.sign+this.wholeNum+this.decimal;
}
} package com.chegg;
public class NumberMain {
public static void main(String[] args) {
Number n1 = new Number(10.02);
Number n2 = new Number(-1009.32);
System.out.println(n1.add(n2));
System.out.println(n1.subtract(n2));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.