When I run my code in the first iteration of the loop, it normally reads the values for that element and stores in arraylist. But after that any scanner is when I reach any scanner, it isn't giving me any chance to enter the variable and gives NoSuchElementException
What I expected was something like this
Enter the number of shapes: 3
Enter 1 for Circle, 2 for Rectangle, 3 for Square: 1
Enter Radius : 1
The area is 3.14 and the perimeter is 6.28
Enter 1 for Circle, 2 for Rectangle, 3 for Square: 2 Enter Length and Breadth: 5 4
The area is 20 and the perimeter is 18
Enter 1 for Circle, 2 for Rectangle, 3 for Square: 3 Enter Side: 2
The area is 4 and the perimeter is 8
Enter the threshold value: 15
The shapes are Rectangle(5,4)
The other classes rectangle and square are similar to circle
class Circle
{
int radius;
public void readAttributes() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Radius: ");
radius = scanner.nextInt();
scanner.close();
}
public double calculateArea() {
return Math.PI * radius * radius;
}
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
public void displayAttributes()
{
System.out.print("Circle("+this.radius+") ");
}
}
public class Q7 {
private static final DecimalFormat decfor = new DecimalFormat("0.00");
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of shapes: ");
int numshapes = scanner.nextInt();
int choice=0;
List<Object> shapes=new ArrayList<>();
for (int i = 0; i < numshapes; i++)
{
System.out.print("Enter 1 for Circle, 2 for Rectangle, 3 for Square: ");
//Second iteration there is NoSuchElementException
choice=scanner.nextInt();
switch (choice)
{
case 1:
Circle circle = new Circle();
circle.readAttributes();
System.out.println("The area is "+decfor.format(circle.calculateArea())+" and the perimeter is "+decfor.format(circle.calculatePerimeter()));
shapes.add(circle);
break;
case 2:
Rectangle rectangle = new Rectangle();
rectangle.readAttributes();
rectangle.displayAreaAndPerimeter();
shapes.add(rectangle);
break;
case 3:
Square square = new Square();
square.readAttributes();
square.displayAreaAndPerimeter();
shapes.add(square);
break;
default:
System.out.println("Invalid Choice! Try Again.");
break;
}
}
System.out.print("Enter the threshold value: ");
//If it reaches here also it gives NoSuchElementException
int threshold=scanner.nextInt();
System.out.print("The shapes are ");
for(Object shape:shapes){
if (shape instanceof Circle) {
Circle circle=(Circle) shape;
if((circle.calculateArea())>threshold)
circle.displayAttributes();
}
else if (shape instanceof Rectangle) {
Rectangle rectangle=(Rectangle) shape;
if((rectangle.calculateArea())>threshold)
rectangle.displayAttributes();
}
else if (shape instanceof Square) {
Square square=(Square) shape;
if((square.calculateArea())>threshold)
square.displayAttributes();
}
}
}
}