So I've been working on this code for a while and it has me a bit lost. Keep in mind I am extremely new to Java and so I'm a bit slow on the uptake. I have created shape classes that implement an interface with getArea, getPerimeter and getDescription methods. There are multiple shapes but that isn't really where the problem is. The problem comes when I attempt to implement switch cases to allow the user to choose which shape he or she wants to add. I am getting the same message as many times as the Array of shapes will allow the address of the Shape I try to add. I realize the mistake I'm making is most likely a beginner one by I would really appreciate some help, Thank you. Also if you could give me a clue on how to sort the Shapes by their Area it would be greatly appreciated.
public class ShapeApp2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Shape[] test = new Shape[10];
System.out.println("Choose a shape or type stop to break away?");
Scanner sc = new Scanner(System.in);
String Shape = sc.nextLine();
for (int i=0; i<test.length; i++) {
switch (Shape) {
case "Rectangle":
System.out.println("You have chosen a Rectangle");
test[i] = new Rectangle();
System.out.println("Enter another one now");
break;
case "Square":
System.out.println("You have chosen a Square");
test[i] = new Square();
System.out.println("Enter another one now");
break;
case "Equilateral Triangle":
System.out.println("You have chosen an Equilateral Triangle");
test[i] = new Equilateral_Triangle();
System.out.println("Enter another one now");
break;
case "Right Triangle":
System.out.println("You have chosen a Right Triangle");
test[i] = new Right_Triangle();
System.out.println("Enter another one now");
break;
case "Isosceles Triangle":
System.out.println("You have chosen an Isosceles Triangle");
test[i] = new Isosceles_Triangle();
System.out.println("Enter another one now");
break;
case "Scalene Triangle":
System.out.println("You have chosen a Scalene Triangle");
test[i] = new Scalene_Triangle();
System.out.println("Enter another one now");
break;
case "Stop":
break;
}
System.out.println(test[i]);
}
}
}
Also here's a couple of the Shape Classes for context.
package shapeapp2;
/**
*
* #author my-pc
*/
public class Rectangle implements Shape {
private double length;
private double width;
private String shapeName;
public Rectangle(){
length = 4.0;
width = 5.0;
shapeName = "Rectangle";
}
public double getArea(){
double Area;
Area = length * width;
return Area;
}
public double getPerimeter() {
double Perimeter;
Perimeter = (2*length) + (2*width);
return Perimeter;
}
public String getDescription() {
return shapeName;
}
}
package shapeapp2;
/**
*
* #author my-pc
*/
public class Square implements Shape {
private double length;
private double width;
private String shapeName;
public Square(){
length = 8.0;
width = 8.0;
shapeName = "Square";
}
public double getArea(){
double Area;
Area = length * width;
return Area;
}
public double getPerimeter() {
double Perimeter;
Perimeter = (2*length) + (2*width);
return Perimeter;
}
public String getDescription() {
return shapeName;
}
}
You are only reading the shape from the user once before the loop. You wanted to read it in the loop. That's the only thing that would make sense.
String Shape = sc.nextLine();
for (int i=0; i<test.length; i++) {
should be
for (int i=0; i<test.length; i++) {
String Shape = sc.nextLine();
Also, you should rename that variable. Shape looks like a classname.
Related
I am currently trying to learn java.
To my current knowledge, I understand it is an OO-based language. I am trying to create a simple class "Circle" with basic parameters (radius, area).
Main function:
import java.util.*;
public class CircleApp
{
public static void main(String[] args)
{
int choice = 1;
while (choice!=4)
{
System.out.println("==== Circle Computation =====");
System.out.println("|1. Create a new circle |");
System.out.println("|2. Print Area |");
System.out.println("|3. Print circumference |");
System.out.println("|4. Quit |");
System.out.println("=============================");
Scanner sc1 = new Scanner(System.in);
choice = sc1.nextInt();
switch (choice)
{
case 1:
{
int rad;
System.out.println("Enter the radius to compute the area and circumference: \n");
Scanner sc2 = new Scanner(System.in);
rad = sc2.nextInt();
Circle circ1 = new Circle(rad);
circ1.setRadius(rad);
circ1.area();
circ1.printArea(circ1);
break;
}
case 2:
{
circ1.area();
Circle.printArea(circ1);
break;
}
case 4:
{
break;
}
default:
{
System.out.println("Choice unknown");
}
}
}
}
}
Circle class:
import java.util.*;
import java.lang.Math;
public class Circle
{
private double radius; // radius of circle
private double area;
private double circumference;
private static int numCircle;
private static final double PI = 3.14159;
// constructor
public Circle(double rad)
{
this.radius = rad;
numCircle++;
}
public Circle()
{
radius = 1.0;
}
// mutator method – set radius
public void setRadius(double rad)
{
this.radius = rad;
}
// accessor method – get radius
public double getRadius()
{
return this.radius;
}
// calculate area
public double area()
{
return area = PI * Math.pow(radius, 2);
}
// calculate circumference
public double circumference()
{
return circumference = 2 * PI * radius;
}
// print area
public static void printArea(Circle c)
{
System.out.println("Radius: " + c.radius);
System.out.println("Area: " + c.area);
}
// print circumference
public void printCircumference()
{
System.out.println("Radius: " + radius);
System.out.println("Circumference: " + circumference);
}
}
Currently, I am trying to create an instance of class Circle within case 1 of my switch case. However, I am unable to get case 2 (calculate and print area) to run properly. While there is the simple workaround of initialising the object outside the switch case, I was wondering if there is a workaround if I were to initialise the object this way instead.
I understand from other sources that the compiler may not respond well to such a scenario as the initialisation of the object is isolated to case 1, which is not guaranteed to be selected first either. Is there a work-around to the issue I am facing or must I initialize the object outside the switch case? Thank you!
I got a task, where I have to calculate the perimeter and area of a given object, that's determined by the user, with accompanying data - side length, radius, etc. To do this I have to do a "GUI" as my teacher said, and to do that, I have to use the Scanner.
Everytime I try to do the second scan, after the user has choosen what object we are dealing with, when it gets to the part, where the user's supposed to input their data about their object, it always crashes, with a java.util.NoSuchElementException error, according to NetBeans. I looked through it, and even copied in the working scanner, but to no avail.
Here's the full code:
package Methods2;
import java.util.Scanner;
public class Methods2 {
public static void main(String[] args) {
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
input1.close();
//decision
if (decider == 1) {
circle();
} else if (decider == 2) {
square();
} else if (decider == 3) {
rectangle();
} else {
System.out.println("There aren't any other options, other than these three.");
}
}
public static void circle() {
//method specific initialization
int radius;
double pi;
double perimeter;
double area;
Scanner input2;
//define
pi = 3.14;
input2 = new Scanner(System.in);
System.out.println("Please type in the radius of the circle!");
radius = input2.nextInt(); //these are where my problem's lie
input2.close();
//calculate
perimeter = 2 * radius * pi;
area = radius * radius * pi;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void square() {
//method specific initialization
int a;
int perimeter;
int area;
Scanner input3;
//define
input3 = new Scanner(System.in);
System.out.println("Please type in one side's length of the square!");
a = input3.nextInt(); //these are where my problem's lie
input3.close();
//calculate
perimeter = 4 * a;
area = a * a;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void rectangle() {
//method specific initialization
int a;
int b;
int perimeter;
int area;
Scanner input4;
//define
input4 = new Scanner(System.in);
System.out.println("Please type in one of the sides' length of the rectangle!");
a = input4.nextInt(); //these are where my problem's lie
System.out.println("Now type the other, non-equal side, compared to the previous one!");
b = input4.nextInt(); //these are where my problem's lie
input4.close();
//calculate
perimeter = 2 * (a + b);
area = a * b;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
}
I have thought about it being multiple Scanner's, but after I realized, that variables don't carry over between methods, unless they're defined within the class, that was swiftly thrown out as a theory. Also, NetBeans didn't mark any problems with that line, so it made even less sense to me.
The reason why your code is "stopping" the scanner, is because you added input1.close();. What .close() does, is that it closes the scanner. Once a scanner is closed, you won't be able to open it again. According to your code, you use the Scanner.. even after it was closed. So to fix your problem, removed the line:
input1.close();
Here is a close up of where you should remove the line:
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
//input1.close(); REMOVE THIS LINE
I am writing a program with separate files in the same package. What I want to do is to use in my Main.java file :
1-Use the values entered by the user create three Triangle objects and stores them in an ArrayList.
2-Display the string representation of each Triangle object in the ArrayList, by calling its toString( ) method and its getArea() method. See the output example below.
I want all the ouput to display after all the inputs. What I mean is that I want the description of each triangle object to be displayed at the end
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("*******************************************************************");
System.out.println("* This program gets input for three triangles from the user. *\n" + "* It then creates three Triangle objects and displays the *\n" + "* description of each.. *");
System.out.println("*******************************************************************");
System.out.println(); // for adding blank line
Scanner input = new Scanner(System. in );
Triangle triangle; //Define the triangle object
ArrayList < GeometricObject > list = new java.util.ArrayList < >();;
for (int i = 1; i < 2; i++) {
System.out.print("Enter the color of a triangle" + i + "(e.g. \"red\"): ");
String color = input.next();
System.out.print("Is the triangle filled (y or n): ");
boolean filled;
String filledString = input.next();
filled = filledString.equals("y"); // condition returns true if "y" is entered
// User input for triangle's 3 sides
System.out.println("Enter the lengths of the three sides of the triangle: ");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
// we need to create the triangle object with the input
triangle = new Triangle(side1, side2, side3);
triangle.setColor(color); // calls setColor from GeometricObject
triangle.setFull(filled); // calls setFilled as well
// Display the triangle, very similar to TestCircleRectangle.java example
System.out.println(); // for adding blank line
System.out.println("Triangle: side1 = " + side1 + "," + " side2 = " + side2 + "," + " side3 = " + side3);
System.out.println(triangle.toString());
System.out.printf("Area = %.2f\n", triangle.getArea());
System.out.println(); // for adding blank line
}
System.out.println("Goodbye...");
}
}
Triangle.java
public class Triangle extends GeometricObject {
// Contains 3 double data fields value to 0
private double side1;
private double side2;
private double side3;
/** Default constructor that creates a triangle
* with default side of 1.0 each
* */
Triangle() {
side1 = 1.0;
side2 = 1.0;
side3 = 1.0;
}
/** parameterized constructor that creates
* a triangle with sides values
* */
Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
/** Getter for side1 */
public double getSide1() {
return side1;
}
/** Setter for side1 */
public void setSide1(double newSide1) {
side1 = newSide1;
}
/** Getter for side2 */
public double getSide2() {
return side2;
}
/** Setter for side2 */
public void setSide2(double newSide2) {
side2 = newSide2;
}
/** Getter for side3 */
public double getSide3() {
return side3;
}
/** Setter for side3 */
public void setSide3(double newSide3) {
side3 = newSide3;
}
/**
* The getArea Method
* Purpose: Computes the area of a triangle from 3 sides
* #return the area of a triangle
*/
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
}
GeometricObject.java
public class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/** Construct a default geometric object */
public GeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with the specified color
* and filled value */
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
this.dateCreated = new java.util.Date();
}
/** Return color */
public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
this.color = color;
}
/** Return filled. Since filled is boolean,
its getter method is named isFilled
*/
public boolean Full() {
return filled;
}
/** Set a new filled */
public void setFull(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}
/**
* Abstract method getArea
*/
/** Return a string representation of this object */
public String toString() {
return "created on " + getDateCreated() + "\ncolor: " + color + " and filled: " + filled;
}
}
(This should probably be more of a comment than an answer, but I am not sufficiently well known in these parts to comment. I am working on that!).
As NotZack said, you haven't actually told us what the problem is. For example, showing us the program's current output compared to what you are aiming for (literally, write down what you want the program to print) would help us know where to start looking.
However, I did notice a few things from quickly looking through your code:
you declare an ArrayList in the main file, but I don't see it being used anywhere. What was the intention of this item?
take a deep, deep look at the following line from main:
for (int i = 1; i < 2; i++)
Get yourself a pen and piece of paper, and write down each value of i in turn which this loop will deal with, bearing in mind the starting value and strictly less than condition. Is this what you want it to do?
Hopefully that gives you something to start working with :)
First you need to add the triangle object to list. And move all the code related to printing triangle move outside the for loop.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<GeometricObject> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
System.out.print("Enter the color of a triangle" + i + "(e.g. \"red\"): ");
String color = scan.next();
System.out.print("Is the triangle filled (y or n): ");
boolean filled = scan.next().equalsIgnoreCase("y");
System.out.println("Enter the lengths of the three sides of the triangle: ");
double side1 = scan.nextDouble();
double side2 = scan.nextDouble();
double side3 = scan.nextDouble();
Triangle triangle = new Triangle(side1, side2, side3);
list.add(triangle);
}
list.forEach(System.out::println);
//Equivalent for above line
/*for(GeometricObject shape: list){
System.out.println(shape);
}*/
}
And also add the toString() method in Triangle class
You don't need to call the toString() method explicitly when you try to print the object it will automatically call the toString() method.
#Override
public String toString() {
return "Triangle: " +
"side1=" + side1 +
", side2=" + side2 +
", side3=" + side3 +
", Area=" + getArea() +
"\n" + super.toString();
}
class TestShapes {
public static void main(String[] args){
Scanner input = new Scanner(System.in); // creates the scanner class
System.out.print("Enter the numer of shapes: "); // asks user for input
int N = input.nextInt(); // stores the user input as N
Shape [] myShape = new Shape[N]; // will create as many shapes (N) in an array
for(int i=0;i<N;i++)
{
System.out.println("Enter the choice (Square, Rectangle, Circle):");
int select = input.nextInt();
if(select == 1)
{
//user wanted a Square
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the side length of the square: ");
double s = input.nextDouble();
myShape[i] = new Square(c,s);
}
else if(select == 2)
{
//user wanted a Rectangle
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the length of the rectangle: ");
double l = input.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double w = input.nextDouble();
myShape[i] = new Rectangle(c,l,w);
}
else if(select == 3)
{
//user wanted a Circle
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the radius of the circle: ");
double r = input.nextDouble();
myShape[i] = new Circle(c,r);
}
}
for(int i=0;i<N;i++) //this will print the details
{
System.out.println("\nShape "+ (i+1)+ ":");
myShape[i].print();
}
}
}
class Shape {
String color;
double area;
public Shape(){ // default constructor
color = "red";
}
public Shape(String c){ // constructor
color =c;
}
public String getColor(){ //accessors
return color;
}
public void setColor(String c){//mutators
color=c;
}
//print method
public void print()
{
System.out.println("Color: "+ getColor());
}
public double area(){
return area;
}
}
class Square extends Shape{ // inherits from the shape class
double sideLength;
public Square(){//default constructor
super();
sideLength = 1;
}
public Square(String c, double s){ //constructor
super(c);
sideLength = s;
}
public double getSideLength(){//accessor
return sideLength;
}
public void setSideLength(double s){//mutator
sideLength = s;
}
public double area(){
return sideLength * sideLength; //calculates the area of the square
}
public void print()
{
super.print();
System.out.println("Side length: " + getSideLength()
+ "\nArea: " + area);
}
}
class Rectangle extends Shape{// inherits from the shape class
double length;
double width;
public Rectangle(){//default constructor
super();
length = 1;
width = 1;
}
public Rectangle(String c, double l, double w){ //constructor
super(c);
length = l;
width = w;
}
public double getLength(){//accessor
return length;
}
public double getWidth(){//accessor
return width;
}
public void setLength(double l){//mutator
length = l;
}
public void setSideLength(double w){//mutator
width = w;
}
public double area(){
return length * width; //calculates thea area of the rectangle
}
public void print()
{ // prints out the information
super.print();
System.out.println("Length: " + getLength() + "\nWidth:"+ getWidth() + "\nArea: "+ area);
}
}
class Circle extends Shape{// inherits from the shape class
double radius;
public Circle(String c, double r){//default constructor
super(c);
radius = 1;
}
public Circle(double r){ //constructor
super();
radius = r;
}
public double getRadius(){//accessor
return radius;
}
public void setRadius(double r){//mutator
radius = r;
}
public void print()
{ // prints out the information
super.print();
System.out.println("Radius: " + getRadius() + "\nArea:"+ area);
}
public double area(){
return 3.14159 * (radius * radius); //calculates the area of the circle
}
}
I have tried every which way to get the Area to return and no matter what I try it will not. Everything else works fine, it prints out everything correctly but not the area. any advice?
Enter the number of shapes: 1
Enter the choice (Square, Rectangle, Circle):
1
Enter the color: red
Enter the side length of the square: 2
Shape 1:
Color: red
Side length: 2.0
Area: 0.0
You are not calculating the area , you should use area() in your print statment
System.out.println("Side length: " + getSideLength() + "\nArea: " + area());
You are printing out uninitialized variable area instead of calling the function area().
System.out.println("Side length: " + getSideLength() + "\nArea: " + area());
That should work, but you should avoid using functions and variables of the same name. getArea() would be a better function name.
So I've spent the last couple days working on this program, and I've hit a roadblock. I am trying to make a calculator that uses specific programs with user input to calculate the Surface area or Volume of multiple shapes. You might recognize this as project 8.5 from the Horstmann java concepts book.
I don't know how to call the methods from one file to another, and need to figure it out.
Here's the code:
import java.util.Scanner;
public class p85SantoCharlie{
public static double sphereVolume(double r){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
double volume = (4/3) * Math.PI * r * r * r;
System.out.println(volume);
return volume;
}
public static double sphereSurface(double r){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
double surface = 4 * Math.PI * r * r ;
System.out.println(surface);
return surface;
}
public static double cyliderVolume(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double volume = Math.PI * r * r * h ;
System.out.println(volume);
return volume;
}
public static double cylinderSurface(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double surface = 2 * Math.PI * r * r * h ;
System.out.println(surface);
return surface;
}
public static double coneVolume(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double volume = Math.PI * r * r * h / 3 ;
System.out.println(volume);
return volume;
}
public static double coneSurface(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double surface = Math.PI * r * (r + Math.pow(( r * r + h * h), .5));
System.out.println(surface);
return surface;
}
}
And here is the main file:
import java.util.Scanner;
public class p85SantoCharlieMain{
public static void main(String[] args){
p85SantoCharlie mainProgram = new p85SantoCharlie();
Scanner in = new Scanner(System.in);
System.out.println("Please select a shape");
System.out.println("your choices are: Sphere, Cylinder, and Cone");
String answer1 = in.next();
String answer1Caps = answer1.toUpperCase();
System.out.println("Fantastic! now select a formula");
System.out.println("your choices are: surface area or volume");
String answer2 = in.next();
String answer2Caps = answer2.toUpperCase();
if (answer1Caps.equals("SPHERE")&& answer2Caps.equals("SURFACE AREA")){
mainProgram.sphereSurface();
}
}
}
Thanks!
If the methods are static you can call them using the class name
p85SantoCharlie.sphereVolume(1.1);
And if they aren't static initialize new class instance and use it to call
p85SantoCharlie p = new p85SantoCharlie();
p.sphereVolume(1.1);
Three problems:
First, all of your calculation methods in p85SantoCharlie are static. You don't need an instance of p85SantoCharlie to invoke them. You should get rid of the line where you do new p85SantoCharlie() and invoke your methods like
p85SantoCharlie.sphereVolume(r);
Second, you have declared your calculation methods as taking parameters, but you don't know those parameters when you invoke them. For example, sphereVolume() is declared as taking double r. But you don't know the value of r until you read it in within the sphereVolume() method. So that can't work. You need to change your main method to ask for the radius, then pass it to sphereVolume as shown above.
Third, all of those Scanners! Get rid of them all except for the one in main. You will be passing in the value of r (or whatever) when you invoke the calculation method. Just use what is passed in.
Ugly, unreadable code.
Java's an object-oriented language. I would expect that you'd start with a Shape interface:
public interface Shape {
double surfaceArea();
double volume();
}
I'd expect to see subclasses for different types that would do the calculation appropriately. Here's a Sphere implementation:
public class Sphere implements Shape {
private final double radius;
public Sphere(double radius) {
if (radius <= 0.0) throw new IllegalArgumentException("radius must be positive");
this.radius = radius;
}
public double surfaceArea() {
return 4.0*Math.PI*this.radius*this.radius;
}
public double volume() {
return 4.0*Math.PI*this.radius*this.radius*this.radius/3.0;
}
}
Here's a Cylinder implementation:
public class Cylinder implements Shape {
private final double radius;
private final double height;
public Cylinder(double radius, double height) {
if (radius <= 0.0) throw new IllegalArgumentException("radius must be positive");
if (height <= 0.0) throw new IllegalArgumentException("height must be positive");
this.radius = radius;
this.height = height;
}
public double surfaceArea() {
return 2.0*Math.PI*this.radius*this.radius + this.radius*this.height;
}
public double volume() {
return Math.PI*this.radius*this.radius*this.height;
}
}
I'd expect to see your driver class interact with Shape objects to solve the problem.
You'll want to consider a virtual constructor/factory for Shape, because you won't want to clutter your code with if/else constructs.
My opinion: Object-oriented programming was invented to solve two problems:
Encapsulation of state and behavior into a single abstract data type.
Inheritance and polymorphism to eliminate if/else and switch statements.
Do not clutter your code with "if sphere and area" kinds of decisions. Let polymorphism handle it for you.
New programmers tend to spend too much time worrying about user interfaces. Concentrate on the functionality and get that working first. Don't create a bunch of text question/answer code and leave the meat of the problem undone.