below I have a small program i wrote for working out the area of shapes....
My question is this the right way to do it, a friend did similar and had multiple shapes which inherited from main shape. OOP? is mine ok as i will only ask the area of a shape and no more? and how would i change this to make it more OO?
Main Prog /////
package areaprog;
import java.util.Scanner;
import java.util.InputMismatchException;
public class Mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
//Menu syntax checking
while (!reader.hasNextDouble())
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
reader.next(); //ask for next token
}
double input = reader.nextDouble();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection and InputMismatch Exception
try {
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextDouble();
double SqAns = AreaCalculator.getSquareArea(s1);
System.out.println("The area of you square is: " + SqAns);
}
}
catch (InputMismatchException e)
{
System.out.println("Why are you trying to be clever? use an interger");
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextDouble();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextDouble();
double RecAns = AreaCalculator.getRectArea(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextDouble();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextDouble();
double TriAns = AreaCalculator.getTriArea(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextDouble();
double CircAns = AreaCalculator.getCircleArea(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
}
}
}
AreaCalculator.java ////
package areaprog;
public class AreaCalculator {
public static double getRectArea(double width, double height) {
double aValue = width * height;
return aValue;
}
public static double getCircleArea(double radius){
double PI = Math.PI;
double aValue = PI * Math.pow(radius, 2);
return aValue;
}
public static double getSquareArea(double side) {
double aValue = Math.pow(side, 2);
return aValue;
}
public static double getTriArea(double base , double height) {
double aValue = (base/2)* height;
return aValue;
}
}
Having multiple classes inheriting from a single base class or interface is definitely a better design here. Use classes to encapsulate given functionality or objects(in that case triangle, square etc. Also when you have multiple classes sharing some functionality better extract it as a common interface to achieve better level of abstraction.
The simple answer is to use an interface of 'shape' like this
interface Shape {
double[] dimensions;
double calcArea();
}
And have all your shapes implement this interface.
say
class Circle implements Shape {
...
}
and implement different calcArea() methods for each shape
In your runner, you init a Circle, box, etc...
When you need area, you don't have to care about which shape is actually behind it, just call the method shape.calcArea() and it will find the right one.
Related
I am trying to integrate the topics like Dynamic Polymorphism, Inheritance and switch statements altogether in a single program where, I am getting an output but the result is always 0 in the console window. There is no error too. May be it is a logical error but I am not sure. I am just at the beginning phase of learning Java.
import java.io.IOException;
import java.util.Scanner;
// Dynamic Polymorphism implementation with switch case
public class Main {
public static void main(String[] args) throws IOException{
Shapes myShape = new Shapes();
Shapes myTriangle = new Triangle();
Shapes myCircle = new Circle();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Shape you would like to get the area of: ");
System.out.println("Your Choices are : 1=Triangle, 2= Circle");
int response = scanner.nextInt();
switch(response)
{
case 1 : System.out.println("Enter the base of the triangle: ");
scanner.nextDouble();
System.out.println("Enter the height of the triangle: ");
scanner.nextDouble();
System.out.println(myTriangle.area());
break;
case 2 : System.out.println("Enter the radius of the circle: ");
scanner.nextDouble();
System.out.println(myCircle.area());
break;
default : System.out.println("Invalid Input");
System.out.println(myShape.area());
}
scanner.close();
}
}
class Shapes {
double base;
double height;
double radius;
public double area() {
System.out.println("Formula for Area of triangle is 1/2 * base * height");
System.out.println("Formula for Area of Circle is 3.14 * radius * radius");
return 0;
}
}
class Triangle extends Shapes{
double x = 0.5*base*height;
#Override
public double area() {
System.out.println("Area of Triangle is : ");
return x;
}
}
class Circle extends Shapes{
double y = 3.14*radius*radius;
#Override
public double area() {
System.out.println("Area of Circle is: ");
return y;
}
}
```
You missed to assign value to the base, height, and radius i.e. you missed something like this:
myTriangle.base = scanner.nextDouble();
Secondly, your area() method should compute on the fly. Otherwise, the area value will always be 0, as originally all the base, height, and radios are 0. So for Triangle class, it should be like this:
class Triangle extends Shapes {
#Override
public double area() {
System.out.println("Area of Triangle is : ");
return 0.5 * base * height;
}
}
You should do the same for Circle.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter circle area");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
double circleArea = RadiusSquared * Math.PI;
return circleArea;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length");
length = scanner.nextDouble();
System.out.print("Enter rectangle width");
width = scanner.nextDouble();
double rectangleArea = length * width;
return rectangleArea;
}
public double getTriangleArea( double base, double height ) {
System.out.println("enter triangle base");
base = scanner.nextDouble();
System.out.println("enter triangle height");
height = scanner.nextDouble();
double triangleArea = (base* height)/2;
return triangleArea;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n" + "9. Exit");
userNum = scanner.nextInt();
if (userNum == 1){
System.out.println(getCircleArea(userNum));
}
else if (userNum == 2){
System.out.println(getRectangleArea(userNum,secNum));
}
else if (userNum == 3){
System.out.println(getTriangleArea(userNum,secNum));
}
else if (userNum == 9){
}
}
}
}
So I wanted it to only be able to put these 4 numbers but I am not sure if this is better than just a while loop, which I think I know how to do. Also what do you think about the actual geometry?
You can try the below code and figure out what's problematic in your code.
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter radius of circle to find area: ");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
return RadiusSquared * Math.PI;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length: ");
length = scanner.nextDouble();
System.out.print("Enter rectangle width: ");
width = scanner.nextDouble();
return length * width;
}
public double getTriangleArea( double base, double height ) {
System.out.print("enter triangle base: ");
base = scanner.nextDouble();
System.out.print("enter triangle height: ");
height = scanner.nextDouble();
return (base*height)/2;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n");
System.out.print("choose a number: ");
userNum = scanner.nextInt();
if (userNum == 1) { System.out.println("Area of circle is " + getCircleArea(userNum)); }
else if (userNum == 2){ System.out.println("Area of rectangle is " + getRectangleArea(userNum,secNum)); }
else if (userNum == 3){ System.out.println("Area of triangle is " + getTriangleArea(userNum,secNum)); }
else System.exit(0);
}
}
}
It's depending on what your needs.
If you want to always display the menu selection bar once after user got the area, while is a must.
If not, just use Map to map each user's selection as to avoid bunches of if else block
//THIS IS FOR OPTION2
//no need the parameter, radius is depending input in the method scope
public double getCircleArea() {//...}
//...
public static void main( String[] args ) {
Map<Integer, Func> map = new HashMap();
map.put(num1, () -> getCircleArea());
//map.put(num2, xxx()) etc
new Geometry().go();
}
private void go() {
//...
map.get(userNum)
}
interface Func{
void execute();
}
(ps, from the code, seen scanner.nextDouble(), scanner.nextInt() to get from input of scanner. I think it is an alert when using different API to maintain the same functionality.
Because it violates encapsulation principle. java.util.Scanner already has the javadoc to interpret these, thus you should check from your side.
)
Hi I was wondering if someone could help me make it so when I choose an option in my code when the program runs, it skips all the other options that weren't chosen and only uses the code inputted by the user. So only the specific parts in the code should be printed but I don't know how to skip over code. There is probably things I should remove and then things I should add but I need help.
package test;
import java.util.Scanner;
import java.text.NumberFormat;
public class Test
{
static Scanner input = new Scanner( System.in );
public static void main(String[] args)
{
//Variables
String Option;
int a;
int Base;
int Height;
int Length;
int Width;
int Radius;
int r;
int b;
double Area;
//Menu
System.out.println("Welcome to the Area Calculator");
System.out.println("");
System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.println("4. Triangle");
System.out.println("5. Quit");
System.out.println("Please enter the number of the shape you would like to calculate the area for.");
Option=input.next();
}
public static void Sqaure(String[] args)
{
System.out.println("Please enter the length of one side.");
int a=input.nextInt();
System.out.println("Please enter the length of one side.");
double area = a*a;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Rectangle(String[] args)
{
System.out.println("Please enter the length.");
int Length=input.nextInt();
System.out.println("Please enter the width.");
int Width=input.nextInt();
double area = Length*Width;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Circle(String[] args)
{
System.out.println("Please enter the radius.");
int r=input.nextInt();
double Radius = r*r;
double area = Math.PI * Radius;
System.out.println("The area of the given shape is " + area + " square units.");
}
{
System.out.println("Please enter the base length.");
int b=input.nextInt();
double Base = b * .5;
System.out.println("Please enter the height lenth.");
int Height=input.nextInt();
double area = Base * Height;
System.out.println("The area of the given shape is " + area + " square units.");
}
}
So, it is clear to me you're very new with Java and you're learning! So I went ahead and made a complete working version of what you are trying to do.
Although it is a simple program Ill go through what each section does.
Prompt Method
Asks the user which area they want to find, this method has the direct answer to your question in the form of a series of if/if else statements. It gets the input from the user and then goes through the series of if/if else statements, seeing if the value entered matches any of them, if it does then it runs that section of code and skips the rest. If a number other then 1-4 is entered, it quits the program (see the else statement), see this page for more info on if statements. I opted for a bunch of if statements but there is a better, cleaner way, but it is a little confusing if you are brand new, see here to learn about those.
Area Methods
These are all pretty much the same except for he way they calculate the areas. They first prompt the user for the required measurements for that shape and assign those entered values to variables, then it prints out the resulting area after running the values through a calculation, then the program stops.
Main Method
All the main method is doing is calling prompt, that keeps it clean, you don't really ever want to do anything but call other methods or create objects in the main method, so most people put the nitty gritty somewhere else and call it.
Below is the working code
Go ahead and paste into a doc and run it, just be aware that I did not bother to add any error catching to keep it simple so keep it to whole numbers without decimals (also called ints, eg. 1, 2, 4, not 4.3, 5.4, etc.)
Side note:
In your methods you have (String args[]) in the brackets, this is not needed, in fact it will cause trouble, that is only used in the main method and is a relatively advanced way of providing input to the program, for now you can keep to leaving the brackets empty.
import java.util.*;
public class Area
{
public static void main(String args[])
{
prompt(); //Calls prompt method
}
//Prompt Method
public static void prompt()
{
int option;
Scanner input = new Scanner(System.in);
//Ask the user which shape they want to find the area of
System.out.println("Select from the following shapes to calulate the area:");
System.out.println("Rectangle -- 1\nCircle -- 2\nTriangle -- 3\nQuit -- 4\n");
System.out.print("Your option: ");
option = input.nextInt();
System.out.println();
//THIS IS THE PART THAT DIRECTLY PERTAINS TO YOUR QUESTION
if(option == 1)
{
rectangle();
}
else if(option == 2)
{
circle();
}
else if(option == 3)
{
triangle();
}
else
{
System.out.println("Program stopped by user"); //For stopping the program when they want to quit instead
System.exit(0);
}
}
//Rectangle Method
public static void rectangle()
{
double h;
double b;
Scanner input = new Scanner(System.in);
System.out.println("RECTANGLE");
System.out.print("Enter Height: ");
h = input.nextDouble();
System.out.print("Enter Base: ");
b = input.nextDouble();
System.out.print("\nArea of Rectangle = " + (h*b) + "\n");
}
//Circle Method
public static void circle()
{
double pi = 3.14;
double radius;
Scanner input = new Scanner(System.in);
System.out.println("CIRCLE");
System.out.print("Enter radius: ");
radius = input.nextDouble();
System.out.print("\nArea of Circle = " + (pi*(radius*radius)) + "\n");
}
//Triangle Method
public static void triangle()
{
double h;
double b;
Scanner input = new Scanner(System.in);
System.out.println("TRIANGLE");
System.out.print("Enter Height: ");
h = input.nextDouble();
System.out.print("Enter Base: ");
b = input.nextDouble();
System.out.print("\nArea of Triangle = " + ((h*b)/2) + "\n");
}
}
package test;
import java.util.Scanner;
import java.text.NumberFormat;
public class Test
{
static Scanner input = new Scanner( System.in );
public static void main(String[] args)
{
//Variables
String Option;
int a;
int Base;
int Height;
int Length;
int Width;
int Radius;
int r;
int b;
double Area;
String [] inputString = new String [50];
//Menu
System.out.println("Welcome to the Area Calculator");
System.out.println("");
System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.println("4. Triangle");
System.out.println("5. Quit");
System.out.println("Please enter the number of the shape you would like to calculate the area for.");
Option=input.next();
switch (Option) {
case "1": Sqaure(inputString);
break;
case "2": Rectangle(inputString);
break;
case "3": Circle(inputString);
break;
default: someExtraFig(inputString);
break;
}
}
public static void Sqaure(String[] args)
{
System.out.println("Please enter the length of one side.");
int a=input.nextInt();
System.out.println("Please enter the length of one side.");
double area = a*a;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Rectangle(String[] args)
{
System.out.println("Please enter the length.");
int Length=input.nextInt();
System.out.println("Please enter the width.");
int Width=input.nextInt();
double area = Length*Width;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Circle(String[] args)
{
System.out.println("Please enter the radius.");
int r=input.nextInt();
double Radius = r*r;
double area = Math.PI * Radius;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void someExtraFig(String ...s)
{
System.out.println("Please enter the base length.");
int b=input.nextInt();
double Base = b * .5;
System.out.println("Please enter the height lenth.");
int Height=input.nextInt();
double area = Base * Height;
System.out.println("The area of the given shape is " + area + " square units.");
}
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm working on a program that calculates the area of either a circle (C), square (S), or rectangle (R), depending on what letter the user inputs. I've tested it and it works fine; the code is below:
import java.util.Scanner;
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
String Shape = input.nextLine();
if (Shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
}
else if (Shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
}
else if (Shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
}
Now, what I want to do is add a loop to the program. For example, if the user inputs C for circle and puts in the number 22 for the radius, they'll get an answer, but I want the program to loop back to the beginning again so that it asks the user "What is your shape?...". Also, if the user types in X instead of C, S, or R, I want the program to quit, but I'm not sure how to add that in, either.
I know that I need to add a 'while' loop, but I was hoping someone could point me in the right direction, because I don't know where to insert that part of the code. Do I add the 'while' loop somewhere at the beginning of the code, after the last "if else" statement, or... Also, I'm not actually sure what to type. Should it be something like,
while (Shape == C, S, R) {
....?
Any help or pointers would be appreciated by any one in the coding community! I will continue to work on this code on my own as well.
I would go for the do, while
So, the program will always do something while the conditions that are set are being accomplished, so you want your program to look something like:
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean thisB = false; /*this is the guy who will tell the loop to stop the execution when the user inserts X*/
String shape;
do{
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
shape = input.next();
if(shape.equalsIgnoreCase("C") || shape.equalsIgnoreCase("S") || shape.equalsIgnoreCase("R")) {
if (shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
} else if (shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
} else if (shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
else if (shape.equalsIgnoreCase("X")) thisB = true;/*or in other words: stop*/
}
while(!thisB);
}
}
Things to consider:
1) Naming conventions, always start variable names with undercase using camelCase, in your example shape started with UpperCase
2) When in a while loop, use only next(), not nextLine() to pick up the values as the latter will duplicate the question in the System.out.Println.
3) The optimum way to do this is to put all your if clauses in a method and call it with the parameter from the Scanner input. Even better would be having a method per shape, as things can get hairy depending on requests
I have written a short program that uses inheritances and interface relationships to calculate the area and the perimeter of user selected shapes. I receive a compile time error when I attempt to compile the following classes.
Class Square
public class Square extends Quadrilateral
{
double side1 =this.side1;
double side2 = this.side2;
double perimeter = this.perimeter;
double area = this.area;
Square(double instanceSide1, double instanceSide2) {
side1 = instanceSide1;
side2 = instanceSide2;
}
#Override
public double area()
{
area = side1 *side2;
return area;
}
#Override
public double perimeter() //math equation for determing perimeter
{
this.perimeter = (side1 * 2) + (side2 * 2) ;
return perimeter;
}
}
Here is my Quad class
public abstract class Quadrilateral implements Polygon{
}
Here is the Polygon Class
public interface Polygon {
abstract void area();
abstract void perimeter();
}
Here is the Tester Class that I've built to run the code.
public static void main(String[] args) //Constructor initalizing main class
{
int numberSides;
int length;
int base;
Scanner sides = new Scanner(System.in); //Initializing Scanner Class
/**
* Do/while loop for selecting a 3 or 4 sided object
*/
do
{
System.out.println("Do you want a 3 or 4 sided shape? (Type either "
+ "3 or 4).");
numberSides = sides.nextInt();
} while (numberSides < 3 || numberSides > 4);
if (numberSides == 3) {
System.out.println("How long are the sides that are the same lenth?");
length = sides.nextInt();
System.out.println("How wide is the base? (whole numbers");
base = sides.nextInt();
IsoscelesTriangle Isoc = new IsoscelesTriangle(length, base);
System.out.println("The area of the isocolese triangle is: " + Isoc.area());
System.out.println("The perimeter of the isocolese triangle is: " + Isoc.perimeter());
} else {
System.out.println("How long are the sides are the same?");
length = sides.nextInt();
System.out.println("How wide is the base?");
base = sides.nextInt();
if (length == base) {
Square Quad = new Square(length, base);
System.out.println("The area of the square is: " + Quad.area());
System.out.println("The perimeter of the square is: " + Quad.perimeter());
} else {
Rectangle Quad = new Rectangle(length, base);
System.out.println("The area of the rectangle is: " + Quad.area());
System.out.println("The perimeter of the rectangle is: " + Quad.perimeter());
}
}
}
}
Your class that implements the interface does not have methods that matches the interface. The interface's methods return void, while the class returns double. They must match exactly, and probably it is the class that's right and the interface that's wrong -- change the interface method declarations to return double.
In the future, you will want to post all error / exception messages if you have a question about them. It will help us save time and get you better answers.