public class Phone {
private String Band;
double price;
String Category;
void setPrice(double newPrice)
{
price = newPrice;
}
double getPrice(){
return price;
}
void setBand(String newBand)
{
Band = newBand;
}
String getBand(){
return Band;
}
void setCategory(String newCategory){
Category = newCategory;
}
String getCategory()
{
return Category;
}
public String Category(double price){
switch(price){
case 1:
if (price>=8000){
Category= "Expensive";
break;
}
case 2:
if(price>=5000 && size<7000){
Category = "Normal";
break;
}
default:
Category = "Cheap";
}
return Category;
}
}
public class TestPhone{
public static void main (String[]args){
Phone PhoneN = new Phone();
PhoneN.setPrice=6500;
System.out.println(PhoneA.getCategory());
}
}
However, the result is null. (when I run the TestPhone class)
Actually , it should be "Normal".
What did I set wrongly in the code?
I just try to use the getter and setter method, and try to apply in the Category also.
Or is it Is this the problem of the data type of price?
Is this the problem of operator?
What's the problem?
Can anyone help me?
Thanks a lot.
Please learn how switch statement works. You can learn from here: Switch in Java
You're passing price in switch(price) but comparing with 1, 2, 3,etc. Here is the problem.
switch-case are always denotes equal. Your program is working like:
if(price == 1) {
if (price>=8000){
Category= "Expensive";
} else if(price == 2) {
if(price>=5000 && size<7000){
Category = "Normal";
} else {
Category = "Cheap";
}
switch is can't be used in this case. Use if else instead.
There are several things wrong with your code.
switch statement over double values - the value must be either char, byte, short, int, Character, Byte, Short, Integer, String, or an enum - you can fix this by declaring the method as public String Category(int price) {}size - probably you meant to use price there?PhoneN.setPrice=6500;, but the Phone class has no field setPrice - you probably wanted to write PhoneN.setPrice(6500);System.out.println(PhoneA.getCategory()); - here again, the symbol PhoneA is never declared, you probably meant System.out.println(PhoneN.getCategory());Fixing all these points you still have the problem that @philoopher97 mentions in his answer: in the switch-case the statements after case 1: are executed when price is 1, which means that the condition price >= 8000 cannot be fulfilled, similar for case 2:
This leads to the last problem: your code never calls the setCategory() or the Category() method and that means that the Category field of the PhoneN object is never set to anything but null.