3

So I'm learning Java and I was hoping to get a little help on how to perfect / enhance a small app I made to calculate the area of a triangle.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.println("What's the base?");
            int base = in.nextInt();
            System.out.println();

        System.out.println("What's the height?");
            int height = in.nextInt();
            System.out.println();

            int area = base * height / 2;

        System.out.println("The area of the triangle is: " +area+ ".");

    }

}

Mind you, I am BRAND NEW to programming in Java, or any language for that matter. If you wouldn't mind, can you explain in the utmost detail on how I can perfect this / make it an easier process?

Thanks a lot!

Matthew
  • 31
  • 1
  • 1
    Step 1: read [code conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html). Your indentation is off and the `+` operator isn't fully surrounded by spaces. – BalusC Aug 22 '10 at 05:35
  • I would add parenthesis to your `area` equation, just to make it clear what your intent is. You could also modify it to allow decimal numbers. – Nate W. Aug 22 '10 at 05:45
  • Step 2: think about types, in `int area = base * height / 2;` what if `base = 5` and `height = 7` –  Aug 22 '10 at 05:45
  • Step N: Formatting strings. `System.out.printf`, you don't even need the `+`, and with `double area`, you can learn to control precision, etc. See http://stackoverflow.com/questions/3377688/what-do-these-symbolic-strings-mean-02d-01d/3377719#3377719 – polygenelubricants Aug 22 '10 at 18:04

4 Answers4

2

There isn't a lot there to simplify and perfect. About the only thing I would modify is the line that calculates the area. Maybe use a float to avoid rounding to int.

float area = (float)(base * height) / 2;

For that matter, you could change the inputs to floats as well:

float base = in.nextFloat();
...
float height = in.nextFloat();

And then change the calculation line to:

float area = base * height / 2;

since now you don't have to cast the inputs.

float will give you single-precision floating point. If you want crazy precision, use double.

Arnold Spence
  • 21,942
  • 7
  • 74
  • 67
  • 1
    `double` isn't "crazy" precision; it should be your default normal precision. You should prefer `double` to `float` in most scenarios. – polygenelubricants Aug 22 '10 at 18:01
  • You may be generally correct but there are two floating types for a reason. They each have trade offs in accuracy, storage size, and speed. These things need to be considered for each usage. You should always know what degree of accuracy your application requires but if one is concerned with storage and performance, measure it. – Arnold Spence Aug 22 '10 at 18:26
  • I guess I should add that a large majority of the Java math functions return doubles so if you are using a lot of those, doubles would be a natural choice. – Arnold Spence Aug 22 '10 at 18:34
  • +1 for @polygenelubricants. @Arnold, _storage size_ ... for what? If you would have one million numbers, you would save almost 4MB. Does it worth? – True Soft Aug 23 '10 at 19:38
  • If you are generating one million numbers only for use in a program running on a typical desktop or laptop computer then obviously no. Some people however use Java in embedded hardware where it does make a difference. Some people also need to serialize their data to store on small capacity storage media or even send it over a low bandwidth connection where it matters quite a lot. – Arnold Spence Aug 23 '10 at 21:19
2

Break it up into Objects.
Your example shows correct usage of syntax, but you haven't demonstrated knowledge of Objects yet.
Consider writing a Triangle class, and implement the area calculation as a member function.
Next you can explore polymorphism.
Refactor the Triangle class by extracting the area calculation into a common interface called Shape.
All classes that implement Shape must provide the method prescribed by the interface for calculating area.
Write a new class called Square that implements the interface Shape.

crowne
  • 8,456
  • 3
  • 35
  • 50
1

area should not be of type int. Make it double.
Edit:

double area = base * height / 2.0;

You can catch the exceptions thrown when the user doesn't input correct values, and ask him again (using a loop).

If the result has too many decimal places, format it:

System.out.println("The area of the triangle is: " +new DecimalFormat("0.000").format(area));
True Soft
  • 8,675
  • 6
  • 54
  • 83
  • Makes no difference if you don't change/cast one of the operands to double. – Mark Peters Aug 22 '10 at 05:47
  • Thanks for the replies! I have gone through them and edited my code to the best of my ability. I changed to float and added decimal formatting. How would I have it so if the are is... well 7 for instance, it won't come out as "7.000" when using +new DecimalFormat("0.000").format(area)? How would I have it so that after each calculation it would restart the program? – Matthew Aug 22 '10 at 20:33
  • Use a format like `0.###` if you don't want to display 0 digits. – True Soft Aug 23 '10 at 19:29
1

You could make it more OO by have a Shape class and Triangle sub class. Calculating area could utilize the Strategy pattern. Hope this helps.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186