call method that rounds java - 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;
}

Related

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.

Commenting a default constructor when writing a class

In my Java basic class my teacher told me to comment any arbitrary choice that I make when I write a default constructor for a class. (She told us that we must create a default constructor for every class that we design) So for example, I'm writing a class named RoomDimension, and I created a default constructor as follows:
public class RoomDimension {
//Fields
private double length; //Length of a carpet
private double width; //Width of a carpet
/**
*
*/
public RoomDimension(){
length = 0.0;
width = 0.0;
}
I'm using here 0.0 as my flag to indicate the user has entered nothing or an invalid input. Should I then comment the fact that 0.0 is used as an indication of an invalid input in the documentation comment(/**/)? I know that if I were to use -1 as my flag (or an initialization of a field in default constructor), I would definitely comment that -1 indicates an invalid input because I made that decision arbitrarily. I'm asking whether 0 has to be commented or not because I don't know if 0 is an arbitrary choice or not. Would you, as a programmer, bother to indicate that? Or, is it okay if I just assume that the user knows it without telling them?
As to whether zero should be commented, I think it would be best to indicate it is a flag in order to remind yourself in the future, or any other programmer that looks at your code.
As for using zero as a flag, I think it would be better practice to throw an exception when length and height are less than or equal to zero. It would be easier to read in the future, and more efficient to handle when a user does enter a non-positive number.
She told us that we must create a default constructor for every class
that we design
And I told for my teacher: Who don't know is teaching, who know is doing!
If you don't create a default constructor, the compiler will do it, did you know? - how about your teacher?
Many tools, which generates, transform data will cry, nags, crash if they don't find a COMPILED "default constructor". But they will completely ignore the comments.
So back to your class:
public class RoomDimension {
static {
System.out.println("I an a static initializer, If the classloader will touch your class, I will be called first! ex. RoomDimension.anyStaticmethod() or before new RoomDimension()");
}
{
System.out.println("I am instance initializer. whenever you call any constructor, I will run before the constructor body, try me with: new RoomDimension()");
}
//Fields
private double length; //Length of a carpet
private double width; //Width of a carpet
public RoomDimension() {
length = 0.0;
width = 0.0;
}
}
By the way in your code:
public RoomDimension() {
length = 0.0;
width = 0.0;
}
it is completely useless, because before constructor, it will be an initialisation and that will do exactly the same, because you have declared as properties and they will be initialize, before constructor:
private double length; //Length of a carpet
private double width; //Width of a carpet
If you want to know it is initialized or not, use Double instead of double and check for null value.
Ex:
private Double length; //Length of a carpet
private Double width; //Width of a carpet
I would set the values of those to be nullable.
public class RoomDimension
{
private double? length;
private double? width;
}
public RoomDimension()
{
}
What this does for you is allow the values of length and width to take the value of null. So when you call the default constructor, they are automatically set to null.
This will help you start thinking in terms of objects, because when you have objects that contain other objects you cant set all the contained objects to 0.0, you just create a null object. Also when you perform actions on that object you just check if its null beforehand this helps to avoid null reference exceptions.

Multiplying user input variables together in another class and then naming that result as a variable

Sorry if this is a bit vague. I am new to learning Java.
In my program I have two classes and one of the classes is for user input. The other class calculates that user input and then returns the calculations to the other class. In my calculations class I'm pretty sure I'm making myself work harder and than I should be. I want to have the result of my user input multiplied together but doing that in the calculations class.
Here is my Calculations class.
class Calculations{
double length, width ;
public double floorArea (double length, double width){
return length * width ;
}
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
public double serviceCharge (double length, double width){
return length * width / 10 + 12.50 ;
}
}
What I want to be able to do is have return length * width = area. Then use that area variable for future reference in the floorAreaCost method and the service charge method. So instead of return length * width * 6.50 I would have area * 6.50
Here's my user input class as well.
import java.util.Scanner;
public class ApartmentUser{
static Scanner input = new Scanner(System.in);
public static void main (String args[]){
int length, width;
System.out.println("Enter the length of the apartment floor: " );
length = input.nextInt();
System.out.println("Enter the width of the apartment floor: " );
width = input.nextInt();
Calculations area = new Calculations();
System.out.println("The area of the apartment floor is: " + area.floorArea(length, width));
Calculations cost = new Calculations();
System.out.println("The cost of the apartment is: " + cost.floorAreaCost(length, width));
Calculations charge = new Calculations();
System.out.println("The service charge cost is: " + charge.serviceCharge (length, width));
}
}
Your methods should call the floorArea method, so for example method shown below
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
would become
public double floorAreaCost (double length, double width) {
return this.floorArea(length, width) * 6.50 ;
}
That way, the floor area calculation is encapsulated inside one method only and can easily change in one step
First of all you shouldn't make so many Calculations objects, one is enough.
So what you should do is give the Calculations class a constructor like this.
class Calculations{
public double length, width, area;
public Calculations (int length, int width) {
this.length = length;
this.width = width;
area = width * length;
}
Now when you create youre Calculations object:
Calculations floor = new Calculations(int length, int width);
You directly have the area calculated and you can call the methods without having to input the parameters, because they're already saved in the Calculations class.
You can also work with multiple "rooms", because the informations are saved in the Calculations class.
Hope i could help you.
As written, your Calculations class defines a "stateless" object.
Within each function, the function parameters length and width
hide the member variables length and width,
so that the member variables are never use at all.
You should be able to delete the declaration of those member variables
without noticing any change in the behavior of your program.
This is not necessarily a bad thing. Stateless classes can be very useful.
For example, because Calculations is stateless, you do not need to
allocate three different instances to perform your three different functions.
You can call all the functions on the same instance, because none of the
functions can affect the "state" of the object and therefore cannot have
any hidden "side effects" on the results of functions called later.
The return from each function is determined just by the values you
pass to its two parameters.
The program does end up multiplying the same length and width together
three times when once would have been enough.
You will hardly notice the extra computing time in this example
(it is vastly overshadowed by everything else going on here),
but if you had to do millions of these calculations for one user input
you might then notice a difference.
One way to avoid the redundant multiplications
is to return area from the floorArea function,
but pass area (not length and width) as a single parameter to
each of the other functions.
You might also consider creating member variables of Calculations
to store the numbers 6.5, 10, and 12.5 that you use in some of your functions.
That would allow you to give those numbers meaningful, descriptive names.
It would also permit a more sophisticated version of the program to accept
new values of those constants to use in a Calculations object,
allowing the store to change its pricing without rewriting its software.
If you set those values during the construction of a Calculations object
and do not change them in any of the other functions, the object
is still stateless.
Or you could decide to change the class some other way. I see at least three other answers already, each of which proposes a legitimate design of a Calculations class, no two of those designs the same.
First off all when you define fields in your class, it's common practice to define the scope of the variable. So it would look something like this. Which only makes the variable accessible within the class, if you would access it from the main method, you should declare em public. But add your area as a variable.
private double area ;
You need to store your calculated Area on the object, use the keyword this for accessing that variable. When operations on the same object is done, it can be fetched in a similar fashion.
Update your code to this:
public double floorArea (double length, double width){
this.area = length * width;
return this.area;
}
public double serviceCharge (){
return this.area / 10 + 12.50 ;
}

String returning a float with one decimal place

I'm trying to format my decimal to show only one decimal place. In my testprogram I set gpa to 3.5454 and it is returning to me the value 3.5454. How do I format it to show 3.5. I tried the code below and it doesn't work. I also tried it in my setGpa method and still no luck
/**
* This method return the student's gpa
* #return This student's gpa
*/
public float getGpa(){
NumberFormat formatter= new DecimalFormat("#0.0");
formatter.format(gpa);
return gpa;
}
Solved! - I just needed to cast type it (float) ((int)(gpa*10) / 10)
You're returning the float again. Maybe you instead wanted to
round the float instead of format it
return the String from formatter.format(gpa)
I think you should try following solution
public static String getGpa(){
NumberFormat formatter= new DecimalFormat("#0.0");
String format = formatter.format(gpa);
return format;
}
Solved! - I just needed to cast type it (float) ((int)(gpa*10) / 10)

implementation formula volume of a sphere with Java and JUnit?

I have to make an implementation to calculate volume of a sphere to be checked with JUnit test, but there are some errors. The formula is correct, but when I test it, it doesn't work :
class VolumeSphere.java
public class VolumeSphere {
public static double volsph(double j) {
double volume;
double const = 1.33;
double phi = 3.14;
volume = const * phi * (j * j * j);
return volume;
}
}
and then this the test file :
VolumeSphereTest.java
import junit.framework.*;
public class VolumeSphereTest extends TestCase {
public VolumeSphereTest(String name) {
super(name);
}
public void testSimple() {
assertEquals(33.4096, VolumeSphere.volsph(2.0));
}
}
when I run the JUnit test, it's said "Expected: (33.4096) but was: (33.4096000005)."
So, what should I do? Thankyou in advance for the help!
The problem is that 33.4096 isn't exactly represented by a double, nor is 1.33, and nor is 3.14. Moreover, the multiplication introduces its own errors. Therefore, the assertEquals needs to be replaced by something that basically means "assert that the value is very close to what we expect".
JUnit has assertEquals(expectedValue, actualValue, errorPermitted) for comparing doubles, which is what you should use here.
In general, double is a poor choice of data type for doing exact arithmetic with numbers expressed as decimals, because it stores binary representations of numbers. If you want accuracy with exact decimals, use BigDecimal instead.
const is a keyword and can't be a name of a variable - pick a different name for your variable.
The problem is that the answer isn't exactly the value you let the JUnit test compare to. The answer is 33.409600000000005 instead of 33.4096. To remedy this, you could use assertEquals(33.4096, VolumeSphere.volsph(2.0), 0.0001);.
This will allow all answers within a difference of 0.0001 around 33.4096. Therefor in this case it will allow 33.4095 to 33.4097.
Also, instead of using double phi = 3.14, you could use Math.PI, which inserts the more significant value of constant pi.

Categories