Setter can't modify the field properly - java

I am encountering a problem when creating a program to solve simple kinematics.
I run the program and find out the fields haven't been modified properly . Here is
the scrap of my program that initialise the object and setting the variables.
public class LinearConstantAcceleration1DKinematics {
private double distance;
private double speed;
private double acceleration;
private double time;
public LinearConstantAcceleration1DKinematics() {
/* initialize the object */
distance = 0;
speed = 0;
acceleration = 0;
time = 0;
}
public void setS(double s) {
this.distance = s;
}
//continue with 3 more setters which is created in the same way ,i have omitted them here
public double getU(){
double u_ans;
u_ans = (distance - 1/2 *acceleration*time*time )/time;
return u_ans;
}
}
And here is the main that uses the methods
LinearConstantAcceleration1DKinematics kinematics = new LinearConstantAcceleration1DKinematics();
kinematics.setS(175);
kinematics.setA(10);
kinematics.setT(5);
System.out.printf(%f\n", kinematics.getU());
The result is 35 which is incorrect.Many thanks for your help.

This has absolutely nothing to do with setter methods -- your division is wrong since 1 / 2 does int division and returns 0 resulting in the equation calculating simply distance / time.
Change to:
u_ans = (distance - 1.0 / 2.0 * acceleration * time * time) / time;
Lesson to learn: don't assume where the error is -- test it. Use a debugger or println statements to check the states of your variables as your program runs.

Related

Java getter with Parameter?

I am new to Java. I know about some core basics of Java such as setter and getter and recently came across a getter with a parameter (not sure if it is correct way of calling it):
public double getDistance(Point p)
{
// what is inside here? Usually without the "Point p" I simply put "return distance;"
}
This method belongs to a class called Point and it is meant to get the calculation of distance from a private method in the same class.
I will appreciate if someone can enlighten me on the getter "parameter" and how I can apply the return in this method.
Thank you.
EDIT: Added the private calculation method
// Compute distance
private double distance(Point p)
{
double xx;
double yy;
double r;
xx = this.x - p.x;
yy = this.y - p.y;
r = Math.sqrt(nx * nx + ny * ny);
return r;
}
I think a simple argument rename will make things clear, you want to calculate the distance between two-points. Specifically, this point and that point. Assuming you have double x and y coordinates in each Point that might look like,
public double getDistance(Point that) {
double tmpX = that.x - this.x;
double tmpY = that.y - this.y;
return Math.sqrt((tmpX * tmpX) + (tmpY * tmpY));
}
Why not use Point2D? It has built-in methods for computing distances from a supplied point to some point you already have.
Point2D pt = new Point2D.Double(10,20);
double distance = pt.distance(new Point2D.Double(20,30));
System.out.println(distance);
Check it out at java.awt.geom.Point2D

Java: Using a double variable to call a double method

The error I'm getting is:
"Cannot invoke yearlyPay() on the primitive type double"
I'm trying to call the method: yearlyPay() on the variable calcPay.
I've created yearlyPay() and it looks as so:
public double yearlyPay(double pay)
{
double yearlyPay = hourlyRate * HOURS_YEAR;
System.out.println("public double yearlyPay(double pay): " + yearlyPay);
System.out.println("");
return yearlyPay;
}
then I have another method where calcPay is located
public double localTax(double calcPay)
{
double pay = calcPay;
double localTax;
if (pay.yearlyPay() < 45000)
{
localTax = (1.15 / 100) * pay;
}
else
localTax = (1.15 / 100) * 45000;
return localTax;
}
I also figured that having
double pay = calcPay
is kinda redundant, so I changed it to
public double localTax(double calcPay)
{ //removed double pay = calcPay
double localTax;
if (calcPay.yearlyPay() < 45000)
{
localTax = (1.15 / 100) * pay;
}
else
localTax = (1.15 / 100) * 45000;
return localTax;
}
But...same thing happened.
I googled the problem (with the error message) but I didn't find anything that helped.
There was a place that said to change double to Double, but I didn't know which ones where to change. So I tried each one, one by one...needless to say that didn't work either.
Any help would be appreciated. There is more to the code (which is homework). I didn't post it all cuz I don't think it's useful. Ask if you need specific though.
Also if this question is similar to this one, let me know, I'll delete this and look at that one. I probably missed it in the 3,000,000+ search results on google.
Only objects have methods.
A double is a primitive not an object.
Your yearlyPay() method is a method of the class you are writing, not of double.
So if yearlyPay() is defined in the same class as the call, you call it as:
double n = yearlyPay(calcPay);
... or if you wrote the method in another class (say, PayCalculator):
PayCalculator payCalculator = new PayCalculator();
...
double n = payCalculator.yearlyPay(calcPay);
... or if the method is in PayCalculator as a static method:
double n = PayCalculator.yearlyPay(calcPay);
Incidentally, it's not a good idea to use floating-point number types for money calculations. Google for reasons.

Calling other methods to main in java

I am having a little issue with formatting returned methods in the main method. I have created the methods and done the calculation, but my issue is if i am calling the other two methods to the main method correctly. I am also having and issue with formatting each method in columns. Do i need to make the columns in the respected methods? or do i need to create them in the main method?
Write a program that analyzes an object falling for 10 seconds. It should contain main and two additional methods. One of the additional methods should return the distance an object falls in meters when passed the current second as an argument. See the formula needed below. The third method should convert meters to feet. You can look up the conversion factor needed online. The main method should use one loop to call the other methods and generate a table as shown below. The table should be displayed in formatted columns with decimals as shown. I believe i am on
SEC METERS FEET
1 4.9 16.1
2 19.6 64.3
3 44.1 144.7
4 78.4 257.2
5 122.5 401.9
6 176.4 578.7
7 240.1 787.7
8 313.6 1028.9
9 396.9 1302.2
10 490.0 1607.6
My code
package week4.yedkois;
public class project3 {
public static void main(String[] args) {
System.out.printf("SEC" + "\n");
meters();
feet();
for (int time = 1; time <= 10; time++) {
System.out.println(time);
}
}
public static void meters() {
double Meters;
double G = 9.8; // meters = .5(9.8)(seconds) ^2
for (int time = 1; time <= 10; time++) {
Meters = (.5 * 9.8 * Math.pow(time, 2));
System.out.printf("%.1f\n", Meters);
}
return;
}
public static void feet() {
double Feet;
double G = 9.8; // meters = .5(9.8)(seconds) ^2
for (int time = 1; time <= 10; time++) {
Feet = (.5 * 9.8 * Math.pow(time, 2) * 3.28084);
System.out.printf("%.1f\n", Feet);
}
return;
}
}
Here is my solution. I use a Tab ("\t") to achieve the same space between the different values. And then I had to redesign your code a little. I use only one if-loop directly in the main-method and hand the current time-value as a parameter into both methods meters() and feet(). That makes it much easier to get all values of one round in line.
Here are some additional remarks:
Java is not C++, so you don't have to use an empty return statement at the end of a method. It's useless there.
In Java variables and method-names always start with a small letter, _ or $. Only class-names and constants start with a capital letter.
Hope this helps for a start.
public class Project3 {
public static void main(String[] args){
System.out.printf("%3s\t%6s\t%6s\n", "SEC", "METERS", "FEET");
for(int time = 1; time <= 10; time++)
{
System.out.print(time + "\t");
meters(time);
feet(time);
System.out.println();
}
}
public static void meters(int time){
double meters;
double g = 9.8; // meters = .5(9.8)(seconds) ^2
meters = (.5 * 9.8 * Math.pow(time, 2));
// the longer the expected maximum length of a result gets
// the higher your reserved number of digits has
// to be, to gain the wanted right bound effect!
System.out.printf("%6.1f\t", meters);
}
public static void feet(int time){
double feet;
double g = 9.8; // meters = .5(9.8)(seconds) ^2
feet = (.5 * 9.8 * Math.pow(time, 2) * 3.28084);
// the longer the expected maximum length of a result gets
// the higher your reserved number of digits has
// to be, to gain the wanted right bound effect!
System.out.printf("%6.1f", feet);
}
}

Why does my function keep failing my JUnit test?

This is one of my classes that I am testing. It keeps failing the calculateVolume() method and I am not sure why.
package shape3D;
public class Sphere implements Cloneable {
private double myRadius;
private double myVolume;
private double mySurfaceArea;
private final static double pi = 3.14;
public static void main(String args[]){
Sphere sphere = new Sphere();
}
public double calculateVolume(){
myVolume = (4/3)*pi*(Math.pow(myRadius,3));
return myVolume;
}
public double calculateSurfaceArea(){
mySurfaceArea = ((4)*(pi)*(Math.pow(myRadius,2)));
return mySurfaceArea;
}
public double getSurfaceArea(){
return this.calculateSurfaceArea();
}
public double getVolume(){
return this.calculateVolume();
}
public void setRadius(double radius2){
myRadius = radius2;
}
public String toString(){
return "Volume: " + this.getVolume() + " Surface area " + this.getSurfaceArea();
}
public Sphere clone (){
Sphere p = new Sphere();
p.setRadius(myRadius);
return p;
}
}
Here is the JUnit test case I am using
public class sphereTest {
#Test
public void testSphere(){
shape3D.Sphere sphere = new shape3D.Sphere();
sphere.setRadius(6);
assertTrue(sphere.calculateSurfaceArea()== 452.16);
assertTrue(sphere.calculateVolume()== 904.32);
The calculateSurfaceArea() stuff passes fine but the volume is failing and I am not sure why.
The calculation
myVolume = (4/3)*pi*(Math.pow(myRadius,3));
Uses integer arithmetic: 4/3 evaluates to 1.
Change it to
myVolume = (4.0/3)*pi*(Math.pow(myRadius,3));
You're doing integer division when calculating the volume truncating the first term of the equation to 1. Replace
myVolume = (4 / 3) * pi * (Math.pow(myRadius, 3)); // 678.24
with
myVolume = (4 / 3.0) * pi * (Math.pow(myRadius, 3)); // 904.31
Due to floating point imprecision you will still need to allow for the difference between the expected & calculated values. You can use this version of assertEquals which allows a delta value to do the comparison - replace
assertTrue(sphere.calculateVolume()== 904.32);
with
assertEquals(sphere.calculateVolume(), 904.32, .02);
Quite aside from the 4/3 integer problem (which I failed to spot): It's not safe to compare two Java double values this way.
If you use assertEquals instead of assertTrue then you might see the problem. I'm betting that it's calculating 4/3 first, then truncating it. And it'll still do this even if you make those into doubles.
Use the overload for assertEquals as mentioned in this question.

call method that rounds java

OK so I can't understand why it says the method isn't being used locally.... The private String formatNumber() method is saying this.
Basically what I need to do is have a method that returns the circumference
- another method that rounds numbers to 2 decimal places and returns a string
- and another method that returns the formatted version of circumference...
It's not hard to see what I'm trying to do, but it gives me the above stated error and I can't figure it out.
//figures out circumference
public double getCircumference(){
circumference = 2 * Math.PI * radius;
return circumference;
}
//takes string and turns back into a double
public double getFormattedCircumference(){
double x = Double.parseDouble(format);
return x;
}
//this method is giving the error of not being used locally...
//method takes double and turns to string so that it can be formatted and it
has to be a string
private String formatNumber(double x){
x = circumference;
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(2);
String format = number.format(x);
return format;
}
You've declared the private method but you've not used it in your current code anywhere and so the compiler is warning you of this (check your program to see if you're calling this method anywhere).
Incidentally, what you're seeing is a warning not an error. Your code should still compile, and the program will still run (if there are no errors present).
Edit 1
You've a serious problem with the method, and maybe more than one, in that it takes in a double parameter and then promptly discards it. Why? If you want to format the number that is passed in as a parameter, then you don't want to discard that parameter. Also, do you want to make this method public so that it can be called by objects outside of this class? Also, will the method have state or will it be stateless? Will it use the fields of the class, or will it only format the number passed into it. If the latter, than it should be a static method.
I got it all figured out. I was making it harder than it actually was.
//figures out circumference
public double getCircumference(){
circumference = 2 * Math.PI * radius;
return circumference;
}
public String getFormattedCircumference(){
return formatNumber(getCircumference());
}
//formats to two decimal places.
private String formatNumber(double x){
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(2);
String format = number.format(x);
return format;
}

Categories