The resulting main() would be just a menu. For example, if you were to add support for parallelograms and trapezoids, you might have a conflict for a variable named height, if you lumped everything into main(). I recommend splitting each calculation into a separate function, to ensure that they do not interfere with each other. I don't see any reason why the inputs should be restricted to ints. Should you later decide to add validation and error handling, you can implement it in one central place. Since there are so many places where you write () followed by scanner.nextInt(), it makes sense to write a function for that. Not only is it easier to see the patten at a glance, it is also more efficient, in that it compiles to a single tableswitch opcode. The compiler will embed just one long string constant in the bytecode.)Ī chain of if-elses would be better written using a switch block. "Enter 3 to find the area of a Triangle or " + "Enter 2 to find the area of a Square, " + "Enter 1 to find the area of a Rectangle, " + Instead of writing the menu as a very long string, it would be more manageable to split it: ("Welcome to the Area Calculator! " + You would be better off naming the class AreaCalculator, which would be more meaningful than Main. Making a package for a one-class program seems like overkill. Int radius = Integer.parseInt(scanner.next()) ("Please enter the radius of the circle: ") Int triangleHeight = Integer.parseInt(scanner.next()) ("Please enter the height of the triangle: ") Int triangleBase = Integer.parseInt(scanner.next()) ("Please enter the base of the triangle: ") Int lengthOfASide = Integer.parseInt(scanner.next()) Int width = Integer.parseInt(scanner.next()) ("Please enter the width of the rectangle: ") Int length = Integer.parseInt(scanner.next()) ("Please enter the length of the rectangle: ") Int userInput = Integer.parseInt(scanner.next()) ("Welcome to the Area Calculator! Enter 1 to find the area of a Rectangle, Enter 2 to find the area of a Square, Enter 3 to find the area of a Triangle or Enter 4 to find the area of a Circle") Scanner scanner = new Scanner(System.in) What this does is that it prompts the user to select a shape, and asks for the details needed to calculate the area of that specific shape. This is a simple Area Calculator coded in Java.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |