【问题标题】:using Java switch statement return null but not the expected outcome使用 Java switch 语句返回 null 但不是预期的结果
【发布时间】:2021-08-22 13:56:36
【问题描述】:
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());
}
}

但是,结果为空。 (当我运行 TestPhone 类时) 实际上,它应该是“正常”。 我在代码中错误地设置了什么? 我只是尝试使用 getter 和 setter 方法,并尝试在 Category 中也应用。
还是这是价格数据类型的问题? 这是运营商的问题吗? 有什么问题? 谁能帮我? 非常感谢。

【问题讨论】:

  • 对不起,应该是 System.out.println(PhoneN.getCategory());
  • edit问题并正确格式化代码。
  • 使用switch 和内部if 有什么意义?您只能使用if else 语句并执行此操作
  • @user14917213 您的测试代码从未为 PhoneN 的类别设置值,因此它为空。
  • 什么是:(price&gt;=5000 &amp;&amp; size&lt;7000)?不应该是:(price&gt;=5000 &amp;&amp; price&lt;8000)size来自哪里?

标签: java switch-statement


【解决方案1】:

请了解switch 语句的工作原理。你可以从这里学习:Switch in Java

您在 switch(price) 中传递了 price,但与 1, 2, 3,etc 进行比较。 这就是问题所在。

switch-case 总是表示相等。您的程序运行如下:

if(price == 1) { 
    if (price>=8000){
    Category= "Expensive";
} else if(price == 2) {
    if(price>=5000 && size<7000){
    Category = "Normal";
} else {
    Category = "Cheap";
}

switch 在这种情况下不能使用。请改用if else

【讨论】:

    【解决方案2】:

    您的代码有几处问题。

    • 它无法编译,因为您不能在 double 值上使用 switch 语句 - 值必须是 char、byte、short、int、Character、Byte、Short、Integer、String 或枚举 -您可以通过将方法声明为 public String Category(int price) {} 来解决此问题
    • 然后 switch 语句尝试使用未定义的符号 size - 可能您打算在那里使用 price
    • 在main方法中你写PhoneN.setPrice=6500;,但是Phone类没有setPrice字段——你可能想写PhoneN.setPrice(6500);
    • 下一行是System.out.println(PhoneA.getCategory()); - 再一次,符号PhoneA 从未声明过,您可能是指System.out.println(PhoneN.getCategory());

    修复所有这些点你仍然有@philoopher97在他的回答中提到的问题:在switch-case中,case 1:之后的语句在price为1时执行,这意味着条件price &gt;= 8000不能已完成,case 2: 类似

    这导致了最后一个问题:您的代码从不调用setCategory()Category() 方法,这意味着PhoneN 对象的Category 字段永远不会设置为null 以外的任何值。

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多