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!
Related
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'm not entirely sure if there is an easier answer to this question and I'm thinking to hard about it or what, but I'm currently programming a rectangular block program to practice Java. It's structured to have 4 methods: getInput, volBlock, saBlock, and display, and I want to use only local variables for these methods. Is there a way that I can utilize getInput to accept and return a single double from the user and if so, how can I use that input in my other methods?
I constructed this code, which uses local variables in getInput() and then passes those values to other methods, but I couldn't figure out a display method so I hard coded it into the calculation methods themselves.
Here is that code:
import java.util.*;
public class Block {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice = "Y";
while (choice.equals("Y")){
getInput();
System.out.println("Would you like to do another calculation?(Y/N): ");
choice = in.next().toUpperCase();
}
System.out.println("Program now ending...");
}
public static void getInput() {
double l, w, h;
Scanner fin = new Scanner(System.in);
System.out.println("Please enter the length, width, and height in that order: ");
l = fin.nextDouble();
w = fin.nextDouble();
h = fin.nextDouble();
volBlock(l, w, h);
surfaceAreaBlock(l,w,h);
}
public static void volBlock(double length, double width, double height) {
double volume;
volume = length * width * height;
System.out.println("The volume is: " + volume);
}
public static void surfaceAreaBlock (double l, double w, double h) {
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
System.out.println("The surface area is: " + surfaceArea);
}
}
I'm sorry if this question is kind of scrambled, I am having a hard time figuring all of this out. I'm quite new to Java.
Any help is appreciated, thank you!
If you're practicing java, you should probably familiarize yourself more with object oriented programming before you go any further, because your code leads me to believe that you're more used to procedural languages (e.g. C, C++, etc). Java doesn't rely on having several static helper methods in its main; the preferred approach is to construct a few classes that perform these calculations for you, and you use the results created by these functions for your basic input/output, which is normally what main is used for.
I implemented a block class to demonstrate what I mean:
public class Block {
private double length;
private double width;
private double height;
public Block(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * length * (height + width) + height * width;
}
/* This is the "display" method that you want */
public String toString() {
return "The volume is: " + getVolume() + "\n"
"The surface area is: " + getSurfaceArea();
}
}
using the Block class, your main becomes much more simple:
public static void main() {
Scanner in = new Scanner(System.in);
char choice = 'y';
do {
System.out.print("Please enter the dimensions of the block: ");
double length = in.nextDouble();
double width = in.nextDouble();
double height = in.nextDouble();
Block block = new Block(length, width, height);
System.out.println(block);
System.out.print("continue (y/n)? ");
choice = in.nextLine.toLowerCase().charAt(0);
} while (choice == 'y');
}
If you return the values from your getInput(), volBlock() and surfaceAreaBlock() methods you might be able to structure the rest as you want to.
For instance surfaceAreaBlock becomes:
public static double surfaceAreaBlock (double l, double w, double h){
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
return surfaceArea;
}
and then when you call surfaceAreaBlock you can do this:
public static void main(String[] args) {
...
double surfaceArea = surfaceAreaBlock();
// Do something with the surface area in this method
...
}
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.
I'm a beginner at Java and I'm having trouble understanding why my "Inflate" and "getVolume" methods aren't working. I'm sure they're just simple problems but I'd still like some help so I can fix my code and improve!
import java.util.Scanner;
public class Balloon
{
public static void main(String[] args)
{
Scanner multiplier = new Scanner(System.in);
System.out.println("How much should the radius be increased by? ");
double amount = multiplier.nextDouble();
double radius = 0;
public void Inflate(double amount);
{
double newRadius = radius + amount;
}
public double getVolume();
{
double sVolume = (4/3)*Math.PI*(newRadius*newRadius*newRadius);
System.out.print(sVolume);
}
}
}
I suppose that Ballon is an object you can inflate and has an state of radius, you can moreover get the volume.
The main method here is only to test if balloon works correctly
public class Balloon {
private double radius = 0;
public static void main(String[] args) {
Scanner multiplier = new Scanner(System.in);
System.out.println("How much should the radius be increased by? ");
Balloon balloon=new Balloon();
double amount = multiplier.nextDouble();
balloon.inflate(amount);
double volume = balloon.getVolume();
System.out.print(volume);
}
public void inflate(double amount) {
radius = radius + amount;
}
public double getVolume() {
double sVolume = (4 / 3) * Math.PI * (Math.pow(radius, 3));
return sVolume;
}
}
Good morning! I have a real quick question. This is about printing the data from a subclass from an array in the main program. Please bear with me i'm rather new to this.
The program should print the Perimeter, the Area and the Average Length of a shape, which is defined in the subclass of the superclass "Shape"
But all it is printing is "Shape."
I know its just a tweak in the syntax but been trying for hours to locate where the problem is. I was wondering if any of you can give me some pointers? Thanks, your help will be much appreciated.
→ To make it easier to understand, I pasted 4 segments of my program,
Main (For collecting the user inputs and printing the results)
The Shape Superclass (Basically for defining the perimeter and area)
The Parallelogram Interface (Basically for the average of the sides lengths)
The Square Subclass (Where all the info is processed)
Main:
package shape;
import java.util.ArrayList;
import java.util.Scanner;
#author Fulltime
public class MainExecute {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Shape> list = new ArrayList<>();
Triangle t;
Square s;
Trapezoid r;
while(true){
Scanner Choice = new Scanner(System.in);
System.out.println("Enter a shape: ");
String choice = Choice.nextLine();
if(choice.equalsIgnoreCase("STOP")){
break;
}
else if(choice.equalsIgnoreCase("triangle")){
System.out.print("Enter base of triangle: ");
double base = Choice.nextDouble();
System.out.print("Enter height of triangle: ");
double height = Choice.nextDouble();
t = new Triangle(base, height);
list.add(t);
}
else if(choice.equalsIgnoreCase("square")){
System.out.print("Enter side of square: ");
double side = Choice.nextDouble();
s = new Square(side);
list.add(s);
}
else if(choice.equalsIgnoreCase("trapezoid")){
System.out.print("Enter length1 of trapezoid: ");
double length1 = Choice.nextDouble();
System.out.print("Enter length2 of trapezoid: ");
double length2 = Choice.nextDouble();
System.out.print("Enter height of trapezoid: ");
double height = Choice.nextDouble();
r = new Trapezoid(length1, length2, height);
list.add(r);
}
}
Shape q;
System.out.println("Shapes: ");
for(int i = 0; i <list.size(); i++){
q = list.get(i);
System.out.println(q.getClass().getName());
if(q.getClass().getName().equalsIgnoreCase("Triangle")){
t=(Triangle)q;
System.out.println("Perimeter: " + t.getPerimeter());
System.out.println("Area: " + t.getArea());
}
if(q.getClass().getName().equalsIgnoreCase("Square")){
s=(Square)q;
System.out.println("Perimeter: " + s.getPerimeter());
System.out.println("Area: " + s.getArea());
System.out.println("Average length of sides: " + s.getAverage());
}
if(q.getClass().getName().equalsIgnoreCase("Trapezoid")){
r=(Trapezoid)q;
System.out.println("Perimeter: " + r.getPerimeter());
System.out.println("Area: " + r.getArea());
System.out.println("Average length of sides: " + r.getAverage());
}
}
}
}
Shape Superclass
package shape;
import java.util.*;
public abstract class Shape {
public abstract double getPerimeter ();
public abstract double getArea ();
public double Perimeter;
public double Area;
public void displayInfo(){
//System.out.println("Perimeter: " + this.getPerimeter());
//System.out.println("Area: " + this.getArea());
}
}
Parallelogram Interface
package shape;
#author Fulltime
public interface Parallelogram {
public double getAverage();
}
Square Subclass
package shape;
import static java.lang.Math.*;
#author Fulltime
public class Square extends Shape implements Parallelogram {
public Square(){}
#Override
public double getPerimeter (){
Perimeter = side * 4;
return Perimeter;
}
#Override
public double getArea (){
Area = side * side;
return Area;
}
#Override
public double getAverage(){
double Sides;
Sides = (this.side + this.side + this.side + this.side) / 4;
return Sides;
}
public double side;
/**
* #return the side
*/
public double getSide() {
return side;
}
/**
* #param side the side to set
*/
public void setSide(double side) {
this.side = side;
}
public Square (double side){
this.side = side;
}
public void printSquare(){
System.out.println("The Perimeter of this shape is " + getPerimeter());
System.out.println("The Area of this shape is " + getArea());
System.out.println("The Average Length of this shape's sides is " + getAverage());
}
}
Use getSimpleName() returns the classname without the package qualification.
if(q.getClass().getSimpleName().equalsIgnoreCase("Triangle")){
}else if(..) // Also use else-if
Or you can use instanceof operator
if(q instanceof Triangle){
//logic here
}else if(..)
Now as a note this is not a good OO design using if-else for everywhere you should reconsider redesign your model.
For example make displayInformation abstract then all concrete subclasses has to override it.
abstract class Shape{
public abstract void displayInformation();
}
Triangle
public class Triangle extends Shape implements whatyouwant {
#Override
public void displayInformation(){
System.out.println("Perimeter: " + this.getPerimeter());
System.out.println("Area: " + this.getArea());
}
}
Square:
public class Square extends Shape ..{
#Override
public void displayInformation(){
System.out.println("Perimeter: " + this.getPerimeter());
System.out.println("Area: " + this.getArea());
System.out.println("Average length of sides: " + this.getAverage());
}
}
So then in your main class you don't have to code any if-else just see polimorphism magic.
for(Shape shape : list){//use enhanced loop
shape.displayInformation();
}