2016-07-06 58 views
-7
public static String getLeastPriceToy(Toy one, Toy two, Toy three, Toy four, 
     String category) { 
    Toy ansToy = one; 
    if(!one.getCategory().equals(category)&& !two.getCategory().equals(category)&& 
     !three.getCategory().equals(category)&&!four.getCategory().equals(category)){ 
     System.out.println("no category found"); 
    } 
    else{ 
    if(two.getCategory().equals(category) && (two.getPrice()*two.getDiscount())<(ansToy.getPrice()*ansToy.getDiscount())){ 
     ansToy =two; 
    } 
    if(three.getCategory().equals(category) && (three.getPrice()*three.getDiscount())<(ansToy.getPrice()*ansToy.getDiscount())){ 
     ansToy =three; 

    } 
    if(four.getCategory().equals(category) && (four.getPrice()*four.getDiscount())<(ansToy.getPrice()*ansToy.getDiscount())){ 
     ansToy =four; 
    } 
    } 
return ansToy.getName(); 

这应该只返回“没有找到类别”,但返回的是第一个字符串的香蕉。我怎样才能消除这样的:如果没有特定的类别,它应该只打印“找不到类别”

enter image description here

+4

'图片在帖子中很有用,但要确保帖子在没有它们的情况下仍然很清晰。如果您发布了代码或错误消息的图片,请直接复制并粘贴或将实际代码或消息输入到帖子中。“基于屏幕截图的操作对我们所有人来说都很困难,而且经常会留下重要信息。你应该更新你的帖子以包含代码并清楚地说明你的问题。 – Obicere

+0

包含你的'main()'方法。 – shmosel

回答

2

假设你打印的getLeastPriceToy()结果,只需更换

System.out.println("no category found"); 

return "no category found"; 
1

如果用return "no category found";替换System.out.println("no category found");你应该获得理想的行为。 现在您打印“香蕉”,因为你总是return ansToy.getName();

0

有一个在代码中没有发生在你正在返回

您已经打印了“没有发现类别”的System.out .... .println( “无类别找到”

但你确实需要添加一行:

回报率( “无类别找到”);

这样说,它migh返回null而不是字符串会更有用。

0

简短的答案已经在这里给出:与return "no category found";

另外更换System.out.println("no category found");,该代码有多种问题,这可能与重新设计来缓解:

  • 调用的方法只有一个,两个或三个参数你需要创建一个总是有一个不能存在的类别的“FakeToy”(你的方法不检查null,所以用null替换其中一个参数会导致NullPointerException)
  • There是没有办法给你比较五种玩具。

此版本处理您的要求,并没有这个限制:

public static String getLeastPriceToy(Set<Toy> toys, String category) { 
    Toy result = null; 
    for(Toy toy: toys) { 
    if(result == null || (toy.getCategory().equals(category) && toy.getPrice() * toy.getDiscount() < result.getPrice() * result.getDiscount())) { 
    result = toy; 
    } 

    if(result == null) { 
    return "no category found"; 
    } 

    return result.getName(); 
} 

这将玩具没有任何代码修改后的任意数量的工作,比你原来的版本更短。

0

在main方法 我检查是否类别匹配或不 如果匹配调用该方法 否则“没有发现类别”

这个逻辑帮我...! Ty all for回答我的问题。