除了最后一种方法之外,一切都工作正常 getPrice()
我回来了int
但我不断收到同样的错误。另外,如果我将保修设置为 false,它仍然返回 (base+((base/100)*10))
public class Machinery extends SaleGroup {
private float serial;
public int base;
private static boolean hasWarranty;
public Machinery(String newItemDescription, float newProductCode,
float newSerial, int newBasePrice) {
super(newItemDescription, newProductCode);
serial = newSerial;
base = newBasePrice;
}
public boolean IncludeWarranty() {
return hasWarranty=true;
}
public boolean ExcludeWarranty() {
return hasWarranty=false;
}
public float getSerial() {
return serial;
}
public int getPrice()
{
if (hasWarranty==true)
{
return (base+((base/100)*10));
}
else if (hasWarranty==false)
{
return base;
}
}
}
我有 3 个类,SaleGroup.java、Machinery.java 和 MachineryTest.java
public abstract class SaleGroup {
private String item;
private float code;
//Constructor with name and code parameters for specifying
//access methods that return the name and code
public SaleGroup(String newItemDescription, float newProductCode)
{
item = newItemDescription;
code = newProductCode;
}
public String getItemDescription()
{
return item;
}
public float getProductCode()
{
return code;
}
public abstract int getPrice();
public String toString()
{
return "Item " + item + "has product code " + code + " and price is" + getPrice();
}
}
MachineryTest.java
import javax.swing.JOptionPane;
public class MachineryTest {
public static void main(String[] args) {
String newItemDescription = "Item";
float newSerial = 4234;
float newProductCode = 3424;
int newBasePrice = 1000;
boolean hasWarranty=true;
Machinery test1 = new Machinery(newItemDescription, newProductCode,
newSerial, newBasePrice);
JOptionPane.showMessageDialog(
null,
"Item: " + test1.getItemDescription() + " Serial: "
+ test1.getSerial() + " Code: "
+ test1.getProductCode() + " Warranty Included: "
+ hasWarranty + " Price " + test1.getPrice());
}
}
*更新:*
除了最后一个方法 getPrice() 之外,一切都工作正常,我返回 int 但我不断收到相同的错误。另外,如果我将保修设置为 false,它仍然返回 (base+((base/100)*10))
最佳答案
如果您的 if
条件都不为 true,则该方法将不会返回任何内容。
编译器的可达性分析不够智能,无法意识到 bool
必须始终为 true
或 false
(特别是因为这并不完全正确)
您可以通过从 else
子句中删除 if
来解决此问题。
当您这样做时,您还可以删除 == true
部分,这是无用的。
关于java - 此方法必须返回 int 类型的结果 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892406/