0
\$\begingroup\$

I'm new to Java and am following a series of lectures on Stanford's YouTube. I know that the code works, but I'd like to know if it can be improved upon.

/*
 * File: PythagoreanTheorem.java
 * Name: Will
 * Section Leader: N/A, I'm freeloading the class off Youtube.
 * -----------------------------
 * This file is the starter file for the PythagoreanTheorem problem.
 */
import acm.program.*;
public class PythagoreanTheorem extends ConsoleProgram {
 public PythagoreanTheorem() {}
 public void run() {
 PythagoreanTheorem myCalculator = new PythagoreanTheorem();
 double a = readDouble("a= ");
 double b = readDouble("b= ");
 if(myCalculator.formula(a,b) == 
 Math.floor(myCalculator.formula(a,b))) {
 println("C= "+(int)myCalculator.formula(a,b));}
 else {
 println("C= "+myCalculator.formula(a,b));}
 }
 private double formula(double x, double y) {
 double c = Math.sqrt(x*x+y*y);
 return c;
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 10, 2018 at 5:53
\$\endgroup\$
4
  • \$\begingroup\$ For those wondering: get your ACM here \$\endgroup\$ Commented Aug 10, 2018 at 6:07
  • \$\begingroup\$ "following a series of lectures on Stanford's Youtube" do you have a transcript of the problem statement to include? Did you write the code? \$\endgroup\$ Commented Aug 10, 2018 at 6:09
  • \$\begingroup\$ I wrote the code. The problem asked to code a calculator to calculate the Pythagorean Theorem. The bit about returning an integer if it could was just me being annoyed at .0's. \$\endgroup\$ Commented Aug 10, 2018 at 6:10
  • \$\begingroup\$ Except some weird formatting in your condition an a one line return in formula there is nothing much to say. But we do not have much to review. \$\endgroup\$ Commented Aug 10, 2018 at 6:28

1 Answer 1

5
\$\begingroup\$

I did not check the acm package but my 2 cents:

No need to instantate a PythagoreanTheorem each time

public void run() {
 PythagoreanTheorem myCalculator = new PythagoreanTheorem();

run is not static, so there already is an instance of PythagoreanTheorem availiable in the method, referencable by this.

So instead of:

if(myCalculator.formula(a,b) == 

You can use

if(this.formula(a,b) ==

Reuse results

You have a few calls to myCalculator.formula(a,b). While a and b do not change. You can store the result in a variable.

double c = myCalculator.formula(a,b)
if(c == Math.floor(c)) 
....
answered Aug 10, 2018 at 6:29
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.