java - Why do I get zero as the result for my PairTester class? -


every time run pairtester class keep getting 0 each result. can tell me why?

public class pair {     private double val1;     private double val2;      public pair(double afirst, double asecond) {         afirst = val1;         asecond = val2;     }      public double getsum() {         double sum = val1 + val2;         return sum;     }      public double getdifference() {         double difference = val1 - val2;         return difference;     }      public double getproduct() {         double product = val1 * val2;         return product;     }      public double getaverage() {         double average = (val1 + val2) / 2;         return average;     }      public double getabsolute() {         double absolute = math.abs(val1 - val2);         return absolute;     }      public double getminimum() {         double minimum = math.min(val1, val2);         return minimum;     }      public double getmaximum() {         double maximum = math.max(val1, val2);         return maximum;     } } 

this tester class:

public class pairtester {     public static void main(string[] args) {         pair mypair = new pair(11, 15);         system.out.println("sum = " + mypair.getsum());         system.out.println("difference = " + mypair.getdifference());         system.out.println("average = " + mypair.getaverage());         system.out.println("absolute = " + mypair.getabsolute());         system.out.println("minimum = " + mypair.getminimum());         system.out.println("maximum = " + mypair.getmaximum());     } } 

your assignments in constructor reversed , due instance fields not getting initialized desired.:

change this

public pair (double afirst, double asecond) {     afirst = val1;     asecond = val2; } 

to:

public pair (double afirst, double asecond) {     val1 = afirst;     val2 = asecond; } 

as no values assigned val1 , val2 instance fields these fields initialized double default value 0.0d.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -