D.Jones
D.Jones

Reputation: 13

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 0.0.

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

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

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

    //tbaseChoice.equals(Tbase);
    //theightChoice.equals(Theight);

}

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

Upvotes: 1

Views: 713

Answers (2)

Shekhar
Shekhar

Reputation: 54

You can try with these code. Maybe this will help you

public class AreaCalculator {
    static double base=0.0;
    static double height=0.0;

    public static void main(String args[]){
        //Scanner object for input
        Scanner scanner=new Scanner(System.in);
        System.out.println("What is the base?");
        base=scanner.nextDouble();
        System.out.println("What is the height?");
        height=scanner.nextDouble();
        System.out.println("BASE:" + base + " " + "HEIGHT:" + height);
        System.out.println("Area is: "+triangleArea());
    }

    public static double triangleArea(){
        return (.5*base*height);
    }
}

Upvotes: 0

Chris Gong
Chris Gong

Reputation: 8229

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.

Upvotes: 2

Related Questions