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开发者_Python百科 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!
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
.
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.
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));
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.
精彩评论