Calculation error in Java - java

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.

Related

Is there any way I can rewrite my methods better?

I'm not entirely sure if there is an easier answer to this question and I'm thinking to hard about it or what, but I'm currently programming a rectangular block program to practice Java. It's structured to have 4 methods: getInput, volBlock, saBlock, and display, and I want to use only local variables for these methods. Is there a way that I can utilize getInput to accept and return a single double from the user and if so, how can I use that input in my other methods?
I constructed this code, which uses local variables in getInput() and then passes those values to other methods, but I couldn't figure out a display method so I hard coded it into the calculation methods themselves.
Here is that code:
import java.util.*;
public class Block {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice = "Y";
while (choice.equals("Y")){
getInput();
System.out.println("Would you like to do another calculation?(Y/N): ");
choice = in.next().toUpperCase();
}
System.out.println("Program now ending...");
}
public static void getInput() {
double l, w, h;
Scanner fin = new Scanner(System.in);
System.out.println("Please enter the length, width, and height in that order: ");
l = fin.nextDouble();
w = fin.nextDouble();
h = fin.nextDouble();
volBlock(l, w, h);
surfaceAreaBlock(l,w,h);
}
public static void volBlock(double length, double width, double height) {
double volume;
volume = length * width * height;
System.out.println("The volume is: " + volume);
}
public static void surfaceAreaBlock (double l, double w, double h) {
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
System.out.println("The surface area is: " + surfaceArea);
}
}
I'm sorry if this question is kind of scrambled, I am having a hard time figuring all of this out. I'm quite new to Java.
Any help is appreciated, thank you!
If you're practicing java, you should probably familiarize yourself more with object oriented programming before you go any further, because your code leads me to believe that you're more used to procedural languages (e.g. C, C++, etc). Java doesn't rely on having several static helper methods in its main; the preferred approach is to construct a few classes that perform these calculations for you, and you use the results created by these functions for your basic input/output, which is normally what main is used for.
I implemented a block class to demonstrate what I mean:
public class Block {
private double length;
private double width;
private double height;
public Block(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * length * (height + width) + height * width;
}
/* This is the "display" method that you want */
public String toString() {
return "The volume is: " + getVolume() + "\n"
"The surface area is: " + getSurfaceArea();
}
}
using the Block class, your main becomes much more simple:
public static void main() {
Scanner in = new Scanner(System.in);
char choice = 'y';
do {
System.out.print("Please enter the dimensions of the block: ");
double length = in.nextDouble();
double width = in.nextDouble();
double height = in.nextDouble();
Block block = new Block(length, width, height);
System.out.println(block);
System.out.print("continue (y/n)? ");
choice = in.nextLine.toLowerCase().charAt(0);
} while (choice == 'y');
}
If you return the values from your getInput(), volBlock() and surfaceAreaBlock() methods you might be able to structure the rest as you want to.
For instance surfaceAreaBlock becomes:
public static double surfaceAreaBlock (double l, double w, double h){
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
return surfaceArea;
}
and then when you call surfaceAreaBlock you can do this:
public static void main(String[] args) {
...
double surfaceArea = surfaceAreaBlock();
// Do something with the surface area in this method
...
}

Why is my code not printing out the new balloon volume?

I'm a beginner at Java and I'm having trouble understanding why my "Inflate" and "getVolume" methods aren't working. I'm sure they're just simple problems but I'd still like some help so I can fix my code and improve!
import java.util.Scanner;
public class Balloon
{
public static void main(String[] args)
{
Scanner multiplier = new Scanner(System.in);
System.out.println("How much should the radius be increased by? ");
double amount = multiplier.nextDouble();
double radius = 0;
public void Inflate(double amount);
{
double newRadius = radius + amount;
}
public double getVolume();
{
double sVolume = (4/3)*Math.PI*(newRadius*newRadius*newRadius);
System.out.print(sVolume);
}
}
}
I suppose that Ballon is an object you can inflate and has an state of radius, you can moreover get the volume.
The main method here is only to test if balloon works correctly
public class Balloon {
private double radius = 0;
public static void main(String[] args) {
Scanner multiplier = new Scanner(System.in);
System.out.println("How much should the radius be increased by? ");
Balloon balloon=new Balloon();
double amount = multiplier.nextDouble();
balloon.inflate(amount);
double volume = balloon.getVolume();
System.out.print(volume);
}
public void inflate(double amount) {
radius = radius + amount;
}
public double getVolume() {
double sVolume = (4 / 3) * Math.PI * (Math.pow(radius, 3));
return sVolume;
}
}

Illegal start of expression when making class for module (java)

I created a module that's called within another module, and it looks something like this:
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
but, I'm getting the error of "illegal start of expression" with the line where I make the method header for the second module. It looks constructed correctly.
Complete code as follows:
//This program will find the area or volume of a circle or sphere, respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or 'N' to Quit");
}
showGoodbye ();
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusOfItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusOfItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere(itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
Specifically, I appear to be having problems in general calling the modules, but none of the text is overly clear and how to make a module fit within the main method, which is where I'm struggling.
There are a lot of errors in your code.
Remove the ; in function. ; is not needed for function.
public static double calculateAnswerSphere(double itemRadius); // remove ;
After showGoodBye() method is being called, you miss to add a close brackets.
You have a typo in this line
system.out.print
It should be System.out.print and so on...

Problems using constructors and getting methods for another class

So i keep getting errors when i try to run the user class saying double is required an no arguments are found. I'm getting errors on lines 17, 40, 42, 44, 46 and 48. They're all errors which say doubles are required. Answers in plain English would be appreciated.
My main class:
import java.util.Scanner;
public class ElectricityCalculatorUser {
//Main method
public static void main (String [] args) {
ElectricityCalculator myCalculator = new ElectricityCalculator();
Scanner input = new Scanner (System.in);
//Input the initial reading
double initialReading;
System.out.print ("What is the inital reading on your electricity meter in kwH? ");
initialReading = input.nextDouble ();
//Input the final reading
double finalReading;
System.out.print ("What is the final reading on your electricity meter in kwH? ");
finalReading = input.nextDouble ();
//Input the number of days
//between readings
double numberOfDays;
System.out.print ("How many days have passed between your initial and final reading? ");
numberOfDays = input.nextDouble ();
//Calculations
double totalElectricityUsed = myCalculator.totalElectricityUsed();
System.out.print ("Total electricity used = " + totalElectricityUsed);
double costOfElectricity = myCalculator.costOfElectricity();
System.out.print ("Cost of electricity = " + costOfElectricity);
double standingCharge = myCalculator.standingCharge();
System.out.print ("Standing charge = " + standingCharge);
double costBeforeVAT = myCalculator.costBeforeVAT();
System.out.print ("Cost before VAT is added = " + costBeforeVAT);
double VAT = myCalculator.VAT();
System.out.print ("Cost of VAT = " + VAT);
double totalCost = myCalculator.totalCost();
System.out.print ("Total cost = " + totalCost);
}
}
My class with all the methods:
public class ElectricityCalculator {
//Attributes
private double initialReading;
private double finalReading;
private double numberOfDays;
//Constructors
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
//Calculating total electricity used
public double totalElectricityUsed () {
return finalReading - initialReading;
}
//Calculating cost of electricity
public double costOfElectricity () {
return totalElectricityUsed * 0.175;
}
//Calculating standing charge
public double standingCharge (double numberOfDays) {
return numberOfDays * 0.25;
}
//Calculating cost before VAT is added
public double costBeforeVAT (double costOfElectricity, double standingCharge) {
return costOfElectricity + standingCharge;
}
//Cost of VAT
public double VAT (double costBeforeVAT) {
return costBeforeVAT * 0.05;
}
//Total cost of electricity used
//including VAT
public double totalCost (double costBeforeVAT, double VAT) {
return costBeforeVAT + VAT;
}
}
In java, if you don't write a constructor, a default constructor will be added automatically for you, and this constructor would be public and takes no argument.
Something like the following:
public ElectricityCalculator () {
}
However, when you define any constructors, the default constructor will be removed. And hence, the only constructor that you have in your class is
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
And therefore
ElectricityCalculator myCalculator = new ElectricityCalculator();
Doesn't match any constructors.
you can simply create the instance after getting the values required to construct the object
ElectricityCalculator myCalculator = new ElectricityCalculator(initialReading, finalReading, numberOfDays);
In addition to Sleiman Jneidi answer, you are calling functions, but dont provide any parameters, as the method definition demands:
double standingCharge = myCalculator.standingCharge();
need to be changed to:
double standingCharge = myCalculator.standingCharge(10.0); //example for 10 days
same problem in the lines 42, 44, 46, 48 of your code
public ElectricityCalculator (double ir, double fr, double nod);
public double standingCharge (double numberOfDays);
public double costBeforeVAT (double costOfElectricity, double standingCharge);
public double VAT (double costBeforeVAT);
public double totalCost (double costBeforeVAT, double VAT);
The constructor and these methods take arguments but you are trying to call them as if they did not.
For the constructor, you can simply move this line
ElectricityCalculator myCalculator = new ElectricityCalculator();
to after you take input from the user so you can pass in the arguments.
// pass arguments here
// v v v
... = new ElectricityCalculator( initialReading , finalReading , numberOfDays );
For the other methods you need to be passing in the results of interim calculations. For example VAT(...) takes a costBeforeVAT which I assume should be the return value of costBeforeVAT(... , ...).
double costBeforeVAT = ...;
// pass argument here
// v
double VAT = myCalculator.VAT( costBeforeVAT );
Note that in some cases you probably do not need these methods to have certain parameters, for example
public double standingCharge () {
return numberOfDays * 0.25;
}
because numberOfDays was already a member of the class ElectricityCalculator and
public double costBeforeVAT () {
return costOfElectricity() + standingCharge();
}
because these methods can be called directly instead of asking for their results to be passed in.
Related: "Passing Information to a Method or a Constructor".

Why is my triangle's area/perimeter 0? [closed]

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.

Categories