D.Jones D.Jones - 2 months ago 4x
Java Question

Geometry Area Calculator

I am trying to make an area calculator in Java that will calculate the area of a triangle based on given dimensions by the user. I can get the user to select the triangle option from a menu and enter their dimensions but when I try to use a method to calculate the area, it only prints out


Scanner tbaseChoice = new Scanner(System.in);
System.out.println("What is the base?");
double selectionb = tbaseChoice.nextDouble();

Scanner theightChoice = new Scanner(System.in);
System.out.println("What is the height?");
double selectionh = theightChoice.nextDouble();

System.out.println("BASE:" + selectionb + " " + "HEIGHT:" + selectionh);



public static void calculateArea() {
double triangleArea = Theight * Tbase;
System.out.print("Area=" + triangleArea);


The problem is that you shouldn't be using the equals method of the Scannerclass to assign values to the Theight and Tbase variables. You should instead be using the = assignment operator to do so instead. So replace theightChoice.equals(Theight); with

Theight = selectionh;

and tbaseChoice.equals(Tbase); with

Tbase = selectionb;

Why your code wasn't working before can be seen from this link, https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

The equals method in the Scanner class is inherited from Java's Object class, which simply just returns a boolean. In your code before, you were checking to see if a Scanner object was equal to another object, but nothing was being done with the boolean value returned. Therefore, your Tbase and Theight variables weren't changing.