Learning / revising Java

So, I am learning Java, and I was hoping to help a little bit on how to improve / improve the small application I made to calculate the area of ​​the triangle.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

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

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

            int area = base * height / 2;

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

    }

}

Keep in mind, I am BRAND NEW for programming in Java or any language in this regard. If you don't mind, can you explain in detail how I can improve this / make it an easier process?

Thank you so much!

+3
source share
4 answers

There is not much to simplify and improve. The only thing I would like to change is the line that calculates the area. Perhaps use float to avoid rounding to int.

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

In this case, you can also change the inputs to floats:

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

Then change the calculation line to:

float area = base * height / 2;

.

float . , double.

+2

.
, .
Triangle -.
polymorphism.
, Shape.
, Shape, , .
Square, Shape.

+2

area int. double.
:

double area = base * height / 2.0;

You can catch the exceptions that are thrown when the user does not enter the 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));
+1
source

You can make it more OO with a class Shapeand subclass Triangle. In the calculation area, you can use the strategy template . Hope this helps.

+1
source

Source: https://habr.com/ru/post/1760955/


All Articles