You are to design a Java application to carry out additions and subtractions for
ID: 3549146 • 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 ( );
Explanation / Answer
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(n um.indexOf(".") );
}
Number add(Number RHS){
double rhs = Double.parseDou ble(RHS.toStrin g());
double orignalNum = Double.parseDou ble(this.toStri ng());
double sum = orignalNum+rhs;
return new Number(sum);
}
Number subtract(Number RHS){
double rhs = Double.parseDou ble(RHS.toStrin g());
double orignalNum = Double.parseDou ble(this.toStri ng());
double difference = orignalNum-rhs;
return new Number(differen ce);
}
public String toString(){
return this.sign+this. wholeNum+this.d ecimal;
}
} 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.prin tln(n1.add(n2)) ;
System.out.prin tln(n1.subtract (n2));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.