DecimalFormats and Return statements - java

For my college class, I have to create a program that calculates the midpoint on a line. I have most of the core program worked out, but I need some help.
public double calculateMidpointX() { // acessor
xmid = (calcX1 + calcX2) / 2.0;
return (xmid);
}
...
DecimalFormat num = new DecimalFormat("###.##");
How do I return xmid with the DecimalFormat("###.##");
Is there a specific syntax I need to be looking at? What if I used System.out.println?

public static void main(String[] args)
{
System.out.println(calculateMidpointX(1.373,3)); // Print 2.19
}
public static double calculateMidpointX(double x, double y) {
DecimalFormat num = new DecimalFormat("###.##");
Double xmid = (x + y) / 2.0;
return (Double.parseDouble(num.format(xmid))); // This return 2.19
}
If i only use return xmid; without format it, it will return 2.1865.

Related

Using return values from methods on ArrayList

Yesterday I posted a question about ArrayList not printing the output from methods, it happened to be just a syntax error. Today, however, I encounter a similar problem with that error fixed. I would appreciate it if someone could tell me what's wrong with this code.
My problem is that the ArrayList prints [0.0, 0.0, 2.75] as opposed to the list of prices I expected.
import java.util.ArrayList;
public class TransitCalculatorTwo {
int numberDays;
int numberRides;
int numberPlanSeven;
int numberPlanThirty;
double totalPriceSeven;
double totalPriceThirty;
double pricePerRideSeven;
double pricePerRideThirty;
double SinglePrice = 2.75;
double sevenDayPrice = 33.0;
double thirtyDayPrice = 127.00;
public int numberPlanSeven(int numberDays) {
int planSeven = (int) Math.ceil (numberDays / 7.0);
return planSeven;
}
public int numberPlanThirty(int numberDays) {
int planThirty = (int) Math.ceil (numberDays / 30.0);
return planThirty;
}
public double totalPriceSeven (int numberPlanSeven, double sevenDayPrice) {
double totalSeven = numberPlanSeven * sevenDayPrice;
return totalSeven;
}
public double totalPriceThirty (int numberPlanThirty, double thirtyDayPrice) {
double totalThirty = numberPlanThirty * thirtyDayPrice;
return totalThirty;
}
public double pricePerRideSeven (double totalPriceSeven, int numberRides) {
double ppRideSeven = totalPriceSeven / numberRides;
return ppRideSeven;
}
public double pricePerRideThirty (double totalPriceThirty, int numberRides) {
double ppRideThirty = totalPriceThirty / numberRides;
return ppRideThirty;
}
public ArrayList<Double> comparePrice() {
ArrayList<Double> prices = new ArrayList<Double>(); for (int i=0; i<1; i++) {
prices.add(pricePerRideSeven);
prices.add(pricePerRideThirty);
prices.add(SinglePrice);
}
return prices;
}
public static void main (String[]args) {
TransitCalculatorTwo customer = new TransitCalculatorTwo();
customer.pricePerRideSeven(66.0, 50);
customer.pricePerRideThirty(127.00, 50);
System.out.println(customer.comparePrice());
}
}
You are not setting variable values in the object you have constructed in main. You are setting values to the local variables and not the objects parameters.Your code must look like this:
public double pricePerRideSeven (double totalPriceSeven, int numberRides) {
this.pricePerRideSeven = totalPriceSeven / numberRides;
return this.pricePerRideSeven;
}
public double pricePerRideThirty (double totalPriceThirty, int numberRides) {
this.pricePerRideThirty = totalPriceThirty / numberRides;
return pricePerRideThirty;
}

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

Add and Multiply Functions in Java return wrong result [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I am doing a very basic Complex Numbers class in Java but when I test my add and multiply functions I don't get the results I expect. I don't understand what is wrong or how to fix it.
When I run the program I get the following output:
a+b: ComplexNumber#1540e19d
a*b: ComplexNumber#677327b6
I should get the proper addition and multiplication of two complex numbers (following the rules of complex numbers of course)
Any help would be much appreciated! Thanks in advance.
Here is the code:
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double r, double i) {
real = r;
imaginary = i;
}
public double real() {
return real;
}
public double imaginary() {
return imaginary;
}
public ComplexNumber add(ComplexNumber c) {
double newr = real + c.real();
double newi = imaginary + c.imaginary();
return new ComplexNumber(newr, newi);
}
public ComplexNumber multiply(ComplexNumber c) {
double newr = real*c.real() - imaginary*c.imaginary();
double newi = real*c.imaginary() + imaginary*c.real();
return new ComplexNumber(newr, newi);
}
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(1.0, 2.0);
ComplexNumber c2 = new ComplexNumber(-1.0, 0.5);
String c1plusc2 = c1.add(c2).toString();
String c1timesc2 = c1.multiply(c2).toString();
System.out.println("a+b :" + c1plusc2);
System.out.println("a*b :" + c1timesc2);
}
}
You need to override the toString method in the ComplexNumber class:
#Override
public String toString() {
return real + " + i*" + imaginary;
}
Your .add() & .multiply() methods return a ComplexNumber object. By default,
System.out.println("a*b :" + c1.multiply(c2));
evaluates to
System.out.println("a*b :" + c1.multiply(c2).toString());
The toString() method is inherited from the Object class (since all classes inherit from Object). And since you're not overriding it in the ComplexNumber class, you get the default return value from Object's toString() method:
ClassName#hashCodeOfTheObject
EDIT:
toString() returns a String. Change
ComplexNumber c1plusc2 = c1.add(c2).toString();
ComplexNumber c1timesc2 = c1.multiply(c2).toString();
to
String c1plusc2 = c1.add(c2).toString();
String c1timesc2 = c1.multiply(c2).toString();
Output:
a+b :0.0 + i*2.5
a*b :-2.0 + i*-1.5

Java – Issue with running a Distance Formula program

I'm making a Distance Formula calculator for practice, but I'm not able to get the program to run on the console when I instantiate the variables. What am I doing wrong here? Any feedback in terms of shortening the code or making it more efficient is also welcome. I've attached it here:
DistFormula.java
public class DistFormula {
public DistFormula() {
}
// Variables
private double x1, x2, y1, y2, diff1, diff2, part1, part2, ans;
// Get first X
public double X1(double x1) {
return x1;
}
// Get first Y
public double Y1(double y1) {
return y1;
}
// Get second X
public double X2(double x2) {
return x2;
}
// Get second Y
public double Y2(double y2) {
return y2;
}
// Set first difference
public double setFirstPart() {
diff1 = x2 - x1;
part1 = Math.pow(diff1, 2);
return part1;
}
// Get first difference
public double getFirstPart() {
return part1;
}
// Set second difference
public double setSecondPart() {
diff2 = y2 - y1;
part2 = Math.pow(diff2, 2);
return part2;
}
// Get second difference
public double getSecondPart() {
return part2;
}
// Set answer
public double setFinalAns() {
ans = Math.sqrt(part1 + part2);
return ans;
}
// Get answer
public double getFinalAns() {
return ans;
}
public String toString() {
return "Distance between coordinates: " + ans;
}
}
Main.java
public class Main {
public static void main(String[] arguments) {
DistFormula newFormula = new DistFormula();
newFormula.X1(10.1);
newFormula.Y1(18.2);
newFormula.X2(12.9);
newFormula.Y2(17.5);
newFormula.setFirstPart();
newFormula.setSecondPart();
newFormula.setFinalAns();
newFormula.toString();
}
}
First I think you would need some way to enter the values of each variable.
public void setX1(double x1) {
this.x1=x1;
}
Also if you want it to be even shorter you could pass these values via the constructor.
public DistFormula(double x1, double x2, double y1, double y2) {
this.x1=x1;
this.x2=x2;
this.y1=y1;
this.y2=y2;
}
You could of course break it down into small parts, but you could also have only one method that calculates the exact answer.
public double calculate() {
return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
}
If you use the first way I mentioned you need to then do (in Main):
DistFormula newFormula = new DistFormula();
newFormula.setX1(10.1);
newFormula.setY1(18.2);
newFormula.setX2(12.9);
newFormula.setY2(17.5);
double answer=newFormula.calculate();
System.out.println("Distance between coordinates: " + answer);
If you use the second way:
DistFormula newFormula = new DistFormula(10.1,18.2,12.9,17.5);
double answer=newFormula.calculate();
System.out.println("Distance between coordinates: " + answer);
First lets try to fix your existing code. For any variable there are corresponding getters and setters but then why?
If a variable is private you cannot access it in other class and moreover in setter you can check the allowed value. For e.g mass of a person cannot be in negative so use of setters is to set the value along with checking some allowed limits. The return type of a setter is always void but not in your code. Getters are used to retrieve the value so return type is non void. You mixed the setter and getters in your code where setters are not setting any value but returning the value which is wrong.
I have modified the code:-
public class DistFormula {
public DistFormula() {
}
// Variables
private double x1, x2, y1, y2, diff1, diff2, part1, part2, ans;
// Get first X
public void setX1(double x1) {
this.x1=x1;
}
// Get first Y
public void setY1(double y1) {
this.y1=y1;
}
// Get second X
public void setX2(double x2) {
this.x2=x2;
}
// Get second Y
public void setY2(double y2) {
this.y2=y2;
}
// Set first difference
public void setFirstPart() {
diff1 = x2 - x1;
part1 = Math.pow(diff1, 2);
}
// Get first difference
public double getFirstPart() {
return part1;
}
// Set second difference
public void setSecondPart() {
diff2 = y2 - y1;
part2 = Math.pow(diff2, 2);
}
// Get second difference
public double getSecondPart() {
return part2;
}
// Set answer
public void setFinalAns() {
ans = Math.sqrt(part1 + part2);
}
// Get answer
public double getFinalAns() {
return ans;
}
public String toString() {
return "Distance between coordinates: " + ans;
}
}
public class Main {
public static void main(String[] arguments) {
//You are trying to achieve sqrt((x2-x1)^2 +(y2-y1)^2)
DistFormula newFormula = new DistFormula();
newFormula.setX1(10.1);
newFormula.setY1(18.2);
newFormula.setX2(12.9);
newFormula.setY2(17.5);
newFormula.setFirstPart();
newFormula.setSecondPart();
newFormula.setFinalAns();
System.out.println(newFormula.toString());
}
}
//Output is now coming as:-
Distance between coordinates: 2.886173937932363
In java for printing value in console you need to do it as:-
System.out.println(newFormula);
No need of calling toString method explicitly. See Why is the toString() method being called when I print an object?
A more efficient way is as under:-
public class TwoDimension {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
public class Main {
public static void main(String[] arguments) {
//You are trying to achieve sqrt((x2-x1)^2 +(y2-y1)^2)
TwoDimension newFormula1 = new TwoDimension();
newFormula1.setX(10.1);
newFormula1.setY(18.2);
TwoDimension newFormula2 = new TwoDimension();
newFormula2.setX(12.9);
newFormula2.setY(17.5);
Double x = newFormula2.getX() -newFormula1.getX();
Double y =newFormula2.getY() -newFormula1.getY();
Double z = Math.sqrt(Math.pow(x, 2)+Math.pow(y, 2)) ;
System.out.println("Distance between coordinates: " + z);
}
}
you need to call System.out.println(newFormula.toString());

Is there an equivalent for toPrecision() in Java?

In porting an algorithm from JavaScript to Java, I've run into the problem that I need a replacement for JavaScript's toPrecision(). The problem is that I don't have a clue how small or large the numbers will be, so I can't use a simple NumberFormat with the right format.
Is there a standard class that offers a similar functionality?
EDIT
Here is what I came up with:
double toPrecision(double n, double p) {
if (n==0) return 0;
double e = Math.floor(Math.log10(Math.abs(n)));
double f = Math.exp((e-p+1)*Math.log(10));
return Math.round(n/f)*f;
}
In principle, it does the right thing, but rounding errors completely ruin it. For example,
toPrecision(12.34567, 3) returns 12.299999999999997
EDIT 2
This version works perfectly for 11 out of 12 test cases...
double toPrecision(double n, double p) {
if (n==0) return 0;
double e = Math.floor(Math.log10(Math.abs(n)));
double f = Math.round(Math.exp((Math.abs(e-p+1))*Math.log(10)));
if (e-p+1<0) {
f = 1/f;
}
return Math.round(n/f)*f;
}
But toPrecision(0.00001234567, 3) still returns 1.2299999999999999E-5 instead of 1.23E-5
Use BigDecimal and setScale() method to set the precision
BigDecimal bd = new BigDecimal("1.23456789");
System.out.println(bd.setScale(3,BigDecimal.ROUND_HALF_UP));
Output
1.235
See
IDEone demo
The simplest solution I came up with for this uses a combination of java.math.BigDecimal and java.math.MathContext like so.
String toPrecision(double number, int precision) {
return new BigDecimal(number, new MathContext(precision)).toString();
}
I'm using this in the dynjs implementation of Number.prototype.toPrecision.
Here's a java solution using String.format.
public static String toPrecision(double d, int digits) {
s = String.format("%."+((digits>0)?digits:16)+"g",d).replace("e+0","e+").replace("e-0","e-");
return s;
}
The .replace is only needed if you want to mimic javascript where it has no leading zero on exponents. If you are just using it for a rounding then return the value as
return Double.parseDouble(s);
Here is some unit test code:
public void testToPrecision() {
String s = NumberFormat.toPrecision(1234567.0,5);
assertEquals("1.2346e+6",s);
s = NumberFormat.toPrecision(12.34567,5);
assertEquals("12.346",s);
s = NumberFormat.toPrecision(0.1234567,5);
assertEquals("0.12346",s);
s = NumberFormat.toPrecision(0.1234567e20,5);
assertEquals("1.2346e+19",s);
s = NumberFormat.toPrecision(-0.1234567e-8,5);
assertEquals("-1.2346e-9",s);
s = NumberFormat.toPrecision(1.0/3.0,5);
assertEquals("0.33333",s);
s = NumberFormat.toPrecision(1.0/3.0,0);
assertEquals("0.3333333333333333",s);
}
You can use double with
double d = 1.23456789;
System.out.println(Math.round(d * 1e3) / 1e3);
prints
1.235
or
System.out.printf("%.3f%n", d);
does the same.
public static void main(String... args) {
System.out.println(round3significant(12345678.9));
System.out.println(round3significant(0.0000012345));
}
public static double round3significant(double d) {
if (d < 100) {
double divide = 1;
while(d < 100) {
d *= 10;
divide *= 10;
}
return Math.round(d) / divide;
} else {
double multi = 1;
while(d > 1000) {
d /= 10;
multi *= 10;
}
return Math.round(d) * multi;
}
}
prints
1.23E7
1.23E-6
You can use NumberFormat to only display as a decimal.
This finally works...
double toPrecision(double n, double p) {
if (n==0) return 0;
double e = Math.floor(Math.log10(Math.abs(n)));
double f = Math.round(Math.exp((Math.abs(e-p+1))*Math.log(10)));
if (e-p+1<0) {
return Math.round(n*f)/f;
}
return Math.round(n/f)*f;
}
import java.text.*;
Class Decimals
{
public static void main(String[] args)
{
float f = 125.069f;
DecimalFormat form = new DecimalFormat("#.##");
System.out.println(form.format(f));
}
}
.## represents upto what decimal places you want
I hope this suits your requirement.

Categories