[英]Why does Java think that the product of all numbers from 10 to 99 is 0?
[英]Why does this return -99 all the time?
我已經有一段時間沒有使用Java了,對此我感到有些沮喪。它總是返回-99,但我不知道邏輯哪里出問題了。
public static void main(String[] args){
System.out.println(shippingCost('P',10));
}
public static int shippingCost(char packageType, int weight)
{
String e1 = "Legal Values: Package Type must be P or R";
String e2 = "Legal Values: Weight < 0";
int cost = 0;
if((packageType != 'P')||(packageType != 'R'))
{
//throw new Exception(e1);
return -99;
} else {
return -1;
}
您的if()應該使用AND
。 由於它現在是OR
,因此您的packageType既不是P也不是R,這總是正確的。
你的話是錯的。 ((Not P)或(Not R))將始終為true,因為其中一個nots將始終為true。
您的if語句正在檢查packageType不等於'P'還是不等於'R'。 這將始終解析為true,這意味着您的函數將始終返回-99。
我認為您打算使用AND
而不是OR
。 嘗試
if((packageType != 'P') && (packageType != 'R'))
^^
因為包裝類型不是'R'!
我認為您的問題出在if語句中。 由於您的條件是“非P或非R”,因此,如果將P傳遞給方法,它將評估為true。 這是因為它不是P,但也不是R,因此它的計算結果為true。
桑尼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.