How to import a variable from a static class - java

This program is supposed to create a fraction when an object is created in the main method and use other methods to add different objects. I am using a class that contains the methods for adding and multiplying the fractions. However, in the class where I have the constructor and the accessors and mutators, I also have another two methods which update the values of numerator and denominator using the methods from the previously mentioned class. How do I access the variables from said class?
This is the class with the constructor and where I am trying to import the variables:
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
// Getters and setters left out for brevity
// Calculate by using the FractionMath class, then update
// the numerator and denominator from the returned Fraction
public void addFraction(Fraction other) {
}
/**
* Updates this fraction by multiplying another fraction
* #param other Fraction to multiple to existing fraction
*/
//Calculate by using the FractionMath class, then update
//the numerator and denominator from the returned Fraction
public void multiplyFraction(Fraction other) {
}
public String toString() {
return numerator + " / " + denominator;
}
}
This is the class with the methods add and multiply:
public class FractionMath {
public static Fraction add(Fraction frac1, Fraction frac2) {
int numerator = frac1.getNumerator() * frac2.getDenominator() +
frac2.getNumerator() * frac1.getDenominator();
int denominator = frac1.getDenominator() * frac2.getDenominator();
return new Fraction(numerator, denominator);
}
public static Fraction multiply(Fraction frac1, Fraction frac2) {
int numerator = frac1.getNumerator() * frac2.getNumerator();
int denominator = frac1.getDenominator() * frac2.getDenominator();
return new Fraction(numerator, denominator);
}
}

Some terminology issues here: There are no static variables in your class. There are static methods.
A static variable would be public static int someNumber = 0;
It is not a static class (Such a thing doesn't really exist in Java), but a class with static methods. There are static inner classes, but they aren't really static in the way you'd have static variables or methods.
To call a static method, you'd just use the class name and the method name, e.g.
Fraction result = FractionMath.add(frac1, frac2);

Related

Java and fractions

I'm trying to add three instance methods to the public interface of class 'Fraction' that all return a 'Fraction' as a result:
add, subtraction and multiplication. is it possible to change it from my current code into instance methods?
I just can't get it to work
Here is my code:
class Fraction {
private Integer numerator;
private Integer denumerator;
public Fraction(Integer numerator, Integer denumerator) {
int gcd = 1;
for (int i = 1; i <= numerator && i <= denumerator; i++) {
if (numerator % i == 0 && denumerator % i == 0)
gcd = i;
}
this.numerator = numerator / gcd;
this.denumerator = denumerator / gcd;
}
public Fraction(Integer numerator) {
this.numerator = numerator;
this.denumerator = 1;
}
public String toString() {
return numerator + "/" + denumerator;
}
public static Fraction add(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
}
public static Fraction subtract(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.denumerator-f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
}
public static Fraction mul(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.numerator,f1.denumerator*f2.denumerator);
}
}
class Main
{
public static void main(String[] arguments)
{
final Fraction HALF = new Fraction(1, 2);
final Fraction THREE_FIFTH = new Fraction(3, 5);
System.out.println(HALF.add(HALF, THREE_FIFTH).toString());
System.out.println(THREE_FIFTH.subtract(HALF, THREE_FIFTH).toString());
System.out.println(HALF.mul(HALF, THREE_FIFTH).toString());
}
}
public static Fraction add(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,
f1.denumerator*f2.denumerator);
}
is a class method (because of the static it does not need an instance to call "on").
Making it instance method would look like
public Fraction add(Fraction other){
return new Fraction(this.numerator*other.denumerator+other.numerator*this.denumerator,
this.denumerator*other.denumerator);
}
of course you do not actually need to write the thiss there, just they emphasize that f1 became the current object, and f2 became the single argument.
Then you could use it as
Fraction HALF = new Fraction(1, 2);
Fraction THREE_FIFTH = new Fraction(3, 5);
System.out.println(HALF.add(THREE_FIFTH));
without repeating HALF (like HALF.add(HALF,THREE_FIFTH) in the original code).
Side comment: class methods (static stuff) can be referred via the name of the class, your original code would be more conventionally called in the form Fraction.add(...):
System.out.println(Fraction.add(HALF,THREE_FIFTH));
(System.out.println() knows that it should call toString() so you do not actually need to do that yourself)

Its possible to define class as double type java?

I have the following class in java :
public class Percentage
{
private double n;
Percentage (double n )
{
this.n=n;
}
public void setN()
{
this.n=n;
}
public double getN()
{
return n;
}
public double percntage ()
{
return this.n/100;
}
}
this Class Percentage will return a double value, but the problem is we can't make any mathematic operation with values like below:
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p*12; // this is error because the class Percentage in not of type double
}
is there someway to make Percentage of type double ?
That is an error because you are multiplying the Percentage object with double value.
The alternative is
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p.getN()*12;
}
You cannot make the class type double. You can perform your operation in the n value instead.
b = p.getN()*12;
you can't define a class as double, because double is a primitive type. What you can do is what the others user suggested:
p.getN();
It will return the double value you need.
No, you can't make it behave like a double, but (like BigDecimal) you can supply methods for performing the relevant operations.
Since your code seems to imply that n = 10 means 10%, i.e. a factor of 0.10, you could make methods like these:
public double of(double value) {
return value * this.n / 100d;
}
public double add(double value) {
return value * (100d + this.n)) / 100d;
}
and then use it like this:
Percentage p = new Percentage(10);
double input = 55;
double d1 = p.of(input); // 10% of 55 = 5.5
double d2 = p.add(input); // 55 + 10% = 60.5

Fraction class trouble (Java)

I am trying to store Fraction objects in an Stack of type Number and then retrieve them to perform arithmetic calculations on them, however, the objects are being converted to type Number when I put them in the stack and I cannot convert them back to type Fraction. The compilation error occurs at line 19 of the source code below. How do I fix this?
Source code:
import java.util.Scanner;
import java.util.Stack;
public class Test{
public static void main(String[] args){
String line = "3/4";
Scanner input = new Scanner(line);
Stack<Number> numbers = new Stack<>();
while (input.hasNext()){
if (input.hasNext("/")){
numbers.push(new Fraction(input.next()));
}
}
if (numbers.peek() instanceof Fraction){
Fraction rhs = numbers.pop();
System.out.println(rhs.getFraction());
}
}
}
The Fraction class exends Number because I need to be able to store Integers, Doubles, Fractions, and Complex numbers to support inter-type mathematical operations. Note that this is not the entire Fraction class, but it is all I used for the compilation of this small test program.
public class Fraction extends Number{
private int numerator;
private int denominator;
public Fraction(String s){
this.numerator = Integer.parseInt(s.substring(0, s.indexOf("/") - 1));
this.denominator = Integer.parseInt(s.substring (s.indexOf("/") + 1, s.length() - 1));
}
public String getFraction(){
String output = this.numerator + "/" + this.denominator;
return output;
}
///Methods for retrieving and changing both the numerator and the denominator
public int getNum(){
return this.numerator;
}
public int getDenum(){
return this.denominator;
}
public void setNum(int num){
this.numerator = num;
}
public void setDenum(int denum){
this.denominator = denum;
}
public int intValue(){
return (Integer) this.numerator/this.denominator;
}
public double doubleValue(){
return this.numerator/this.denominator;
}
public long longValue(){
return this.numerator/this.denominator;
}
public short shortValue(){
return 0;
}
public float floatValue(){
return 0.0f;
}
}
This has nothing to do with Fraction. If Fraction subclasses Number then you should be able to cast from Number to Fraction. So something like
Fraction rhs = (Fraction) numbers.pop()

Initialize complex number JAVA

I want to ask, how can I initiallize final fields ONE and ZERO, if I want to use them as neutral elements for addition and multiplication like in Ring
They must be costantly
enter image description here
public class ComplexNumber {
/**Constant for multiplication. Value 1*/
//public final ComplexNumber ONE;
/**Constant for addition. Value 0 */
//public final ComplexNumber ZERO;
/**The real value of ComplexNumber! FINAL*/
private final double a;
/**The imaginary value of ComplexNumber! FINAL*/
private final double b;
/**
* This Constructor initializes real and imaginary values of ComplexNumber
* #param a double real value
* #param b double imaginary value
*/
ComplexNumber(double a, double b) {
this.a = a;
this.b = b;
//this.ONE = new ComplexNumber(1,0); //TODO ask
// this.ZERO = new ComplexNumber(0);
}
/**
* This Constructor initializes imaginary value of CompexNumber
* #param b double imaginary value
*/
ComplexNumber(double b){
this.a = 0;
this.b = b;
//this.ONE = new ComplexNumber(1,0); //TODO ask
// this.ZERO = new ComplexNumber(0);
}
Thank you!
If you want to make constants out of them, declare and initialize them like this:
public static final ComplexNumber ONE = new ComplexNumber(1, 0);
public static final ComplexNumber ZERO = new ComplexNumber(0, 0);
static means that the field is class-specific and not instance-specific. final means the reference can't be reassigned. For a real constant, the instance must be immutable as well, which I think your code is doing since a and b are not accessible from outside your class.
only constructor is the way to initialize your final variables in Java.
because A final can only be initialize once of its life Cycle you cannot re-initialize it again .
So, Calling Constructor using parameter is a best way to initialize.
public class ComplexNumber {
final double realPart;
final double imgPart;
public static final ComplexNumber REAL_ONE = new ComplexNumber(1, 0);
public static final ComplexNumber ZERO = new ComplexNumber(0, 0);
public ComplexNumber(double realPart, double imgPart) {
this.realPart = realPart;
this.imgPart = imgPart;
}
public ComplexNumber(double imgPart) {
this(0, imgPart);
}
}
To make your code readable you can rename your field names to real and img part.
And use constructor chaining so that you can reuse the existing constructor.
EDIT
public class ComplexNumber {
final double realPart;
final double imgPart;
public static final ComplexNumber REAL_ONE = new ComplexNumber(1, 0);
public static final ComplexNumber ZERO = new ComplexNumber(0, 0);
public ComplexNumber(double realPart, double imgPart) {
this.realPart = realPart;
this.imgPart = imgPart;
}
public static ComplexNumber createRealComplexNumber(double realPart) {
return new ComplexNumber(realPart, 0.0);
}
public static ComplexNumber createImgComplexNumber(double imgPart) {
return new ComplexNumber(0.0, imgPart);
}
}
If you ever want to create a complex number with only real part, you'll not be able to overload constructor that only has real part, because the same signature is already being used. You can use this method

Java interfaces and downcasting

I have a Fraction class which implements an interface named FractionInterface. In FractionInterface I have specified a method FractionInterface add(FractionInterface secondFraction);. I am having trouble implementing this method in my Fraction class.
public class Fraction implements FractionInterface
{private int num; // Numerator
private int den; // Denominator
public int getNum()
{
return this.num;
} // end getNum
public int getDen()
{
return this.den;
} // end getDen
public FractionInterface add(FractionInterface secondFraction)
{
FractionInterface result = (num*secondFraction.getDen()+secondFraction.getNum()*den)/
(den*secondFraction.getDen());
}
}
I get an error saying "Type mismatch: cannot convert from int to FractionInterface.", I was given a hint to downcast the parameter secondFraction from FractionInterface to Fraction but i'm not sure how to do that. Could someone explain what I am doing wrong?
What do you expect this to do?
FractionInterface result = (num*secondFraction.getDen()+secondFraction.getNum()*den)/
(den*secondFraction.getDen());
The right side is a number, the left side is an object. The compiler has no way to know how to convert a number into a Fraction object.
You need a constructor in your Fraction class that accepts a numerator and denominator:
public Fraction(int numerator, int denominator) {
num = numerator;
den = denominator;
}
and then do this
FractionInterface result = new Fraction(THENUMERATOR, THEDEMONIMATOR);
which I think, for you, is
FractionInterface result = new Fraction(
(num*secondFraction.getDen()+secondFraction.getNum()*den),
(den*secondFraction.getDen());

Categories