Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to write a code for where the user inputs two legs of a triangle and the program will calculate the hypotenuse, area, and perimeter. However, all my outputs are 0.
Here is the code:
package practice;
public class RightTri {
double leg1;
double leg2;
double hypotenuse;
double Area;
double Perimeter;
public RightTri() {
leg1=0;
leg2=0;
hypotenuse=0;
}
public double getArea() {
double Area= leg1*leg2*0.5;
return Area;
}
public double getHypotenuse() {
double Hypotenuse=Math.sqrt(Math.pow(leg1, 2.0)+Math.pow(leg2, 2.0));
return Hypotenuse;
}
public double getPerimeter() {
double Perimeter= leg1+leg2+hypotenuse;
return Perimeter;
}
}
package practice;
import javax.swing.JOptionPane;
public class RightTriTest {
public static void main (String args[]) {
RightTri Test=new RightTri();
String a= JOptionPane.showInputDialog ("Leg 1?");
Double leg1=Double.parseDouble(a);
String b= JOptionPane.showInputDialog ("Leg 2?");
Double leg2=Double.parseDouble(b);
System.out.println("The hypotenuse is " +Test.getHypotenuse());
System.out.println("The area is " +Test.getArea());
System.out.println("The perimeter is " +Test.getPerimeter());
}
}
You have defined your triangle's values to be 0:
public RightTri()
{
leg1=0;
leg2=0;
hypotenuse=0;
}
You never change any of them, so when you call getArea()...
public double getArea()
{
double Area= leg1*leg2*0.5;
return Area;
}
...you get 0 because 0 * 0 * 0.5 is zero.
You seem to have confused local variables in the main method with the ones in your triangle object. Try making a more sensible constructor instead:
public RightTri(double leg1, double leg2) {
this.leg1 = leg1;
this.leg2 = leg2;
}
And calling it from main, for example like this:
RightTri a = new RightTri(4, 6);
System.out.println(a.getArea());
Alternatively, since the fields are not private, you could access them directly from main:
Test.leg1 = 4.5;
But this isn't very idiomatic to Java, so I recommend using the constructor.
public RightTri()
{
leg1=0;
leg2=0;
hypotenuse=0;
}
All you values are 0 in your no-arg constructor
You should use a constructor like this
public RightTri(double leg1, double leg2)
{
this.leg1 = leg1;
this.leg2 = leg2;
}
Then in the main do something like this
String a= JOptionPane.showInputDialog ("Leg 1?");
Double leg1=Double.parseDouble(a);
String b= JOptionPane.showInputDialog ("Leg 2?");
Double leg2=Double.parseDouble(b);
RightTri Test = new RightTri(leg1, leg2);
System.out.println("The hypotenuse is " +Test.getHypotenuse());
System.out.println("The area is " +Test.getArea());
System.out.println("The perimeter is " +Test.getPerimeter());
That happens because the values that you obtain for leg1 and leg2 are not being assigned in your "Test" object. I recommend you to create a couple setters in your class RightTri:
public void setLeg1(Double leg1){
this.leg1 = leg1;
}
public void setLeg2(Double leg2){
this.leg2 = leg2;
}
And then assign the values from RightTriTest:
public static void main (String args[]) {
RightTri Test=new RightTri();
String a= JOptionPane.showInputDialog ("Leg 1?");
Double leg1=Double.parseDouble(a);
Test.setLeg1(leg1);
String b= JOptionPane.showInputDialog ("Leg 2?");
Double leg2=Double.parseDouble(b);
Test.setLeg2(leg2);
System.out.println("The hypotenuse is " +Test.getHypotenuse());
System.out.println("The area is " +Test.getArea());
System.out.println("The perimeter is " +Test.getPerimeter());
}
You've said it yourself: constructing a zero triangle is meaningless. Why not drop your default (i.e. no argument) constructor altogether?
Supply this instead:
public RightTri(double leg1, double leg2)
{
this.leg1 = leg1;
this.leg2 = leg2;
this.hypotenuse = Math.sqrt(leg1 * leg1 + leg2 * leg2);
}
Notice that I've bought the hypotenuse calculation inside the constructor. You might even want to bring the setting of Area and Perimeter inside it too: then you can guarantee that the object is in a well-formed state on construction at the expense of virtually negligible overhead. Of course, you'll need to adjust your various get... functions.
I've also dropped the pow functions. The way you have them with 2.0 as the argument will invoke a slow computation: it's much quicker for powers of 2 to multiply the numbers yourself.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
I got the below question for an assignment in my Java class.
Write a Java method to find & print the area of a circle when user input the radius.
I came up with 2 solutions,
Solution 1: Call a void method where the method does all the inputs and calculations and prints the output.
import java.util.*;
class Example{
public static void area(){
Scanner input = new Scanner (System.in);
double area = 0;
double radius = input.nextInt();
area = 3.14 * radius * radius;
System.out.println("Area is: " + area);
}
public static void main(String args[]){
System.out.println("Input the radius: ");
area();
}
}
Solution 2: Call a parameterized double method. Here the input is fed to the main method and calculation is done in the double method and value is returned back to the main method.
import java.util.*;
class Example{
public static double area(double r){
double area = 0;
area = 3.14 * r * r;
return area;
}
public static void main(String args[]){
System.out.println("Input the radius: ");
Scanner input = new Scanner (System.in);
double radius = input.nextDouble();
System.out.println("Area is: " + area(radius));
}
}
I am wondering what is the best coding practice. Solution 1 or 2 and why is that? Thanks in advance for all the responses.
The second version is better because it separates the concerns of (a) calculating the area from (b) what to do with the results.
You don't need to declare double area = 0 before you assign a value to it. You can simply write:
double area = 3.14 * r * r;
But, in fact, you don't need to declare a variable at all in that method. You can return the value.
public static double area(double r){
return 3.14 * r * r;
}
You can also use the Math constant for PI:
public static double areaOfCircle(double r){
return Math.PI * r * r;
}
I'm writing a program for an assignment and am getting incorrect calculations when I run the program.
The program I'm creating is designed to take user input to control a robot and then calculate and print out the following:
Distance traveled
Horizontal position
Vertical position
Battery Usage
The calculation for battery usage is working fine, but the rest of the calculations print the value 0.0 or -0.0
My code is spread across two classes, one containing the constructor method and all of the calculations, while the other contains the main method with code to take user input and print results.
Class containing the Constructor and all of the Calculations:
class RobotMovement{
private double angle;
private double speed;
private double time;
private double distance;
//Constructor method
public RobotMovement(double a,double s,double t){
angle = a;
speed = s;
time = t;
}
//Set methods
public void setAngle(double a){
angle = a;
}
public void setSpeed(double s){
speed = s;
}
public void setTime(double t){
time = t;
}
public void setDistance(double d){
distance = speed * time;
}
//Get methods
public double getAngle(){
return angle;
}
public double getSpeed(){
return speed;
}
public double getTime(){
return time;
}
public double getDistance(){
return distance;
}
//Calculation Methods
public double calcHorizontal(){
return distance * Math.sin(angle);
}
public double calcVertical(){
return distance * Math.cos(angle);
}
public double calcBattery(){
return time * Math.pow(speed,2) * 3.7;
}
}
Class containing Main method:
import java.util.*;
class RobotUser{
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
//Getting user input for the Robot object
System.out.println("\nPlease enter the Angle, Speed and Time you wish the Robot to travel");
System.out.println("\nAngle:");
double angle = scan.nextDouble();
System.out.println("\nSpeed:");
double speed = scan.nextDouble();
System.out.println("\nTime:");
double time = scan.nextDouble();
//Instantiates RobotMovement
RobotMovement Robot = new RobotMovement(angle,speed,time);
System.out.println("\nThe Robot moved " + Robot.getDistance() + " meters!");
System.out.println("\nThe Robots horizontal position is " + Robot.calcHorizontal());
System.out.println("\nThe Robots vertical position is " + Robot.calcVertical());
System.out.println("\nThe Robot used " + Robot.calcBattery() + " seconds of idle time");
}
}
I think your issue is that you are never calculating the distance traveled, and in java the default value for the distance variable then becomes 0.0. So when you ask to calculate the answer for the other 3 methods, you're multiplying each answer by 0.0 and that's how you end up with those results. calcBattery is the only one that does not use the distance variable.
TLDR; just calculate the distance before you ask to calculate the other values.
Basically, there are two classes... One is supposed to work out the area of a circle, the other is for the user to enter the number of circles they want to work with, the radius of each circle and the program is then to display it after each other. At the end, the biggest area is displayed. It displays an error that the method in the first class cannot be applied to the given types...
The first class:
public class Prac4 {
private float radius;
public Prac4() {
}
public void setRadius(float radius) {
this.radius = radius;
}
public float getRadius() {
return radius;
}
public double calcArea() { //Getting errors if I don't use double
return 3.14* radius*radius; //Getting errors if I try to use pow function as pow(radius, 2) even with java.lang.math
}
}
So the calcArea is the part being called in the second function to calculate the area of the circles. I have tried making it public float calcArea() but that brought up a whole new set of errors.
The second class:
import java.util.*;
public class Prac5
{
public Prac5() { //Not sure why, but my lecturer says it should be like this
}
public static void main(String[] args) {
int circleNum;
float radius=0;
float big=0;
Scanner scan =new Scanner(System.in);
Scanner rad =new Scanner(System.in);
System.out.print("Enter the number of circles: ");
circleNum = scan.nextInt();
for(int i=1; i<circleNum;i++)
{
Prac4 circle1 = new Prac4(); //Trying to call in the other class
System.out.printf("Enter the circle %d radius: ", i);
circle1.setRadius(radius);
System.out.printf("The radius is: %f", rad);
double area = circle1.calcArea(radius); //This is where the error occurs, the .calcArea is highlighted
if (big<area)
{
big = area;
}
}
System.out.printf("The biggest area is: %f",big);
}
}
I've declared the area as a double thinking it would work because calcArea is a double, and there was errors when I tried keeping everything as a float or double. I'm still new to java, so maybe there is something I'm missing?
Edit: The full error -
method calcArea in class Prac4 cannot be applied to given types;
required: no arguments
found: float
Reason: actual and formal argument lists differ in length
This call
double area = circle1.calcArea(radius);
doesn't match the method defined in the Prac4 class, which takes no arguments:
public double calcArea()
Change it to :
double area = circle1.calcArea();
You don't have to pass the radius to calcArea(), since you're already passing it to setRadius here - circle1.setRadius(radius); - which stores the radius in the circle1 instance.
From what I am seeing, you are calling this: double area = circle1.calcArea(radius); but you have this: public double calcArea() {, that is, your calcArea does not take any parameters. Calling it like so: double area = circle1.calcArea(); should fix the problem.
My homework is to calculate taxes and surcharges for a jewelry store that is replenishing its stock, and I have run into a slight snag. I am using a method called calcExtraTax three times to calculate the labor rate and state and federal taxes. I then need to take the results of each instance of that method and pass the value into the appropriate variable in my main method. This is what my code looks like right now (evidently not complete):
import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.JOptionPane;
public static void main(String[] args)
{
double stateRate = 0.1;
double luxuryRate = 0.2;
double laborRate = 0.05;
double extraCharge;
int numOrdered;
double diamondCost;
double settingCost;
double baseCost;
double totalCost;
double laborCost;
double stateTax;
double luxuryTax;
double finalAmountDue;
Scanner keyInput = new Scanner(System.in);
System.out.println("What is the cost of the diamond?");
diamondCost = keyInput.nextDouble();
System.out.println("What is the cost of the setting?");
settingCost = keyInput.nextDouble();
System.out.println("How many rings are you ordering?");
numOrdered = keyInput.nextInt();
baseCost = diamondCost + settingCost;
calcExtraCost(baseCost, laborRate);
laborCost = extraCharge;
calcExtraCost(baseCost, stateRate);
stateTax = extraCharge;
calcExtraCost(baseCost, luxuryRate);
luxuryTax = extraCharge;
totalCost = baseCost + laborCost + stateTax + luxuryTax;
finalAmountDue = numOrdered*totalCost;
JOptionPane.showMessageDialog(null, "The final amount due is = " + finalAmountDue);
}
public static void calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
???????????
}
what i'm trying to figure out is what else i need to put in my secondary method in order to be able to pass the result into a different tax cost variable each time depending on the rate variable used in the formula.
You don't need to do anything special with your calcExtraCost apart from changing the return type to double and returning the calculated value. For example
public static double calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
double tax = //some calculations
return tax
}
So this method would return the calculated value.
In your main method you need to store that value to the appropriate double that you want. For example if you want to calculate the luxuryTax, then you do something like:
luxuryTax = calcExtraCost(baseCost, luxuryRate);
Also some advice, instead of making your method static, make it a non-static method, and create an object of the class where your method is defined, and call the method on that object.
For example if the class where you defined your method is called Tax, then you create an object of Tax:
Tax tax = new Tax();
and call calcExtraCost on that object:
tax.calcExtraCost();
This way you remove the static part of the method. So your method signature becomes like this:
public double calcExtraCost(double diamond, double rate)
You can return the value of diamond*rate from your helper method by changing its signature from void to double and adding a return statement:
public static double calcExtraCost(double diamond, double rate)
{
return diamond * rate;
}
Now you can assign the result of a call to the variable in your main method:
laborCost = calcExtraCost(baseCost, laborRate);
I'm making an BMI calculator for a diet programming I'm making for a piece of coursework. Originally I was making a a couple variables public static to get variables from another class. My BMI calculator worked fine this way.
I then figured out that I could use a get method (for more marks). So I changed by the previous variables to private and used a get method. But when I run this program I get NaN when the program prints out the the variable that holds the BMI, this never happened before!
Can anyone help?
import java.util.Scanner;
public class Weight {
private Scanner input;
private String readInput;
private String userWeightIsPounds;
private String userWeightIsStones;
private Scanner input2;
public static double userWeight;
public Weight(){
userWeightIsPounds = ("Pounds");
userWeightIsStones = ("Stones");
}
public void findOutUserWeightMessage(){
System.out.println("Firstly Do you weigh yourself in pounds or stones?");
}
public void findOutUserWeight(){
input = new Scanner (System.in);
readInput = input.nextLine();
if(readInput.equals(userWeightIsPounds)){
System.out.println("Ok then, enter your weight in pounds please.");
}
if(readInput.equals(userWeightIsStones)){
System.out.println("Ok enter your weight in stones please.");
}
input2 = new Scanner (System.in);
userWeight = input2.nextFloat();
if (userWeight > 20){
System.out.println("You've enetered your weight as " + userWeight + " lbs. I'll save that information for later.");
}else{
userWeight = userWeight * 14;
System.out.println("I've converted your weight into pounds for you. You weigh " + userWeight + " lbs. I'll save that information for later.");
}
}
public double static getUserWeight(){
return userWeight;
}
}
And there is come code the the class that does the calculations. Ignore some of the println's I was trying to find out what was happening with my variables.
public class BMI {
private double userHeightSqaured;
private double bmiMutiplier;
private double weightDivideHeight;
private double userBmi;
private double userWeightBmi;
private double userHeightBmi;
BMI(){
bmiMutiplier = 703;
userWeightBmi = Weight.getUserWeight();
userHeightBmi = Height.getUserHeight();
}
public void startUpBmiMessage(){
System.out.print("Lets start with your BMI then shall we? ");
}
public void calculateUserBmi(){
System.out.println("userWeightBmi is " + userWeightBmi);
System.out.println("userWeightBmi is " + userHeightSqaured);
userHeightSqaured = userHeightBmi * userHeightBmi;
System.out.println("userHeightSqaured is " + userHeightSqaured);
weightDivideHeight = userWeightBmi/userHeightSqaured;
System.out.println("weightDivideHeight is " + weightDivideHeight);
userBmi = weightDivideHeight * bmiMutiplier;
System.out.println("weightDivideHeight is " + weightDivideHeight);
System.out.println("bmiMutiplier is " + bmiMutiplier);
}
public void calculateUserBmiMessage(){
System.out.println("Your bmi is " + userBmi);
}
}
It sounds like you're trying to write a Java program that performs some calculations, and the result of your calculation is NaN - you can refer to the question In Java, what does NaN mean? for some info on NaN.
As for resolving your problem without seeing any code, and assuming your calculation worked fine with the same input before, it sounds like your switch from public static variables to private ones with getters has probably left some of your variables uninitialized, so their value defaults to 0 - Division by 0 is a common cause of NaN.
The reason for the NaN is that this statement:
weightDivideHeight = userWeightBmi/userHeightSqaured;
divided zero by zero. In other words userWeightBmi and userHeightSqaured were both zero at that point.
The root problem seems to be that you haven't got your head around the difference between static and instance variables. And when you should / should not use the two kinds of variable.