Reputation: 1
I want to set property of class based on this first switch. If vrsta (eng. type) is krug (circle) I want to have its diameter (r) as property of its type Figura (eng. Figure), if it is pravouganonik(eng. rectangle) I want to have its sides: a and b, and if it kvadrat(eng. square) I want to have its side value (str). How can I fix my switch, it gives me compile error. Illegal start of type on switch(vrsta){, it gives me expected on same line, orphaned case on case "krug". Thank you so much!
import java.util.Scanner;
class Figura{
String boja,vrsta;
Double povr;
switch (vrsta){
case "krug":
Double r;
break;
case "pravougaonik":
Double a,b;
break;
case "kvadrat":
Double str;
break;
}
Figura(String b, String v){
Scanner sc=new Scanner(System.in);
boja=b;
vrsta=v;
switch (vrsta){
case "krug":
r=sc.nextDouble();
povr=r*r*3.14;
break;
case "pravougaonik":
a=sc.nextDouble();
b=sc.nextDouble();
povr=a*b;
break;
case "kvadrat":
str=sc.nextDouble();
povr=str*str;
break;
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
Figura f1=new Figura(sc.nextLine(),sc.nextLine());
System.out.println(f1.povr);
}
}
Upvotes: 0
Views: 78
Reputation: 3332
The error compile error. Illegal start of type on switch(vrsta)
is raised because it doesn't follow the convention for defining members. Instead, it should be wrapped inside a member function.
A member should be defined like this
class A {
modifiers type name;
}
A simple solution for this problem is to use inheritance. Create a base class Figure
, and create other child classes Circle
, Square
, Rectangle
from it.
class Figure {
// base class
}
class Circle extends Figure {
double radius;
}
class Rectangle extends Figure {
double length;
double width;
}
class Square extends Figure {
double side;
}
In main you can create the object of the Class that you need
public static void main(String[] args) {
Figure f;
int type = 1; // set type as required
switch(type) {
case 1:
f = new Circle();
break;
case 2:
f = new Rectangle();
break;
case 3:
f = new Square();
break;
default:
f = new Figure();
}
}
Upvotes: 1