Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning / Revising Java [closed]

Tags:

java

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!

like image 939
Matthew Avatar asked Nov 26 '25 18:11

Matthew


1 Answers

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.

like image 57
Arnold Spence Avatar answered Nov 28 '25 07:11

Arnold Spence



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!