mercredi 24 février 2021

Need Help - Java simple regular shape area calculator with if statement

I am trying to finish up a java project making a programme that takes input for a regular shape between 3 & 6 sides then takes length of sides, calculates and prints. Its my first time using java so I'm a bit unsure about the errors from line 25 onwards that I'm getting like "'x' cannot be resolved to a variable". I think I have done the maths right so It's probably a simple fix but I've been trying for a while now and have resorted to asking for clarification. The only stipulation of the task is that an if statement is required to run code implementing the appropriate formula for the given number of sides, and store the result in a variable.

Here is the code in full so far:

import java.util.Scanner;

public class RegularShapeArea {

    public static void main(String[] args) {
    
    //user input takes number of sides between 3 & 6 and stores in 'sides'
        
    System.out.println("How many sides does the shape have (between 3 and 6)? ");
    Scanner sidenum = new Scanner(System.in);
    double sides = sidenum.nextDouble();
    
    //if statement to determine user input is between 3 & 6 or presents and error message
    
    if((sides <3) || (sides >6)) { 
        System.out.println("The value entered was not between 3 & 6.");
    }
    //else statement runs user input for length of sides if it is within correct parameters and storees value in 'lengths'
    else {
        System.out.println("How long is each side? ");
        Scanner sidelength = new Scanner(System.in);
        double length = sidelength.nextDouble();
    }

    if (length == 3) {
        double calculation = (Math.sqrt(3)/4) * (length *length);
    }
    else if (length == 4) {
        calculation = (length * length);
    }
    else if (length == 5) {
        calculation = (Math.sqrt(5 * (5 + 2 * (Math.sqrt(5)))) * length * length) / 4;
    }
    else if (length == 6){
        calculation = ((3 * Math.sqrt(3) * (length * length)) / 2);
    }
    
    
    System.out.Println("The surface are of a shape with" + sides + "sides, each of length" + sidelength + "is " + calculation);
    }

}

Any help with this would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire