在我開始之前,我想說明一下,在編寫代碼時,我非常習慣於初學者,所以如果我所問的內容看起來非常基本,我很抱歉。初學Java:從方法中返回值
這就是說我正在努力與我的代碼中的返回方法。我可以編寫這個程序,而不用像我那樣將它分解成方法,但我被告知,編寫代碼時很好的做法是將它拆分成方法,以便調試更容易。
下面的代碼似乎有一些主要缺陷。
public static boolean hybridNot()
{
String typeCar = input("Hybrid or Electric?");
boolean electric = false;
if (typeCar.equalsIgnoreCase("Electric"))
{
electric = true;
}
else if (typeCar.equalsIgnoreCase("Hybrid"))
{
electric = false;
}
else
{
print("Sorry I didn't understand that");
}
return;
}
public static boolean solarNot()
{
String panelsMaybe = input("Solar panel?");
boolean solarPanel = false;
if (panelsMaybe.equalsIgnoreCase("Yes"))
{
solarPanel = true;
}
else if (panelsMaybe.equalsIgnoreCase("No"))
{
solarPanel = false;
}
else
{
print("Sorry I didn't understand that");
}
return;
}
public static int discountNot()
{
final int basicPrice = 20000;
final int electricCost = 2000;
final int solarCost = 5000;
boolean electric = hybridNot();
boolean solarPanel = solarNot();
int totalPrice;
if ((solarPanel = true) || (electric = true))
{
totalPrice = basicPrice + solarCost + electricCost - 500;
}
else if ((solarPanel = true) || (electric = false))
{
totalPrice = basicPrice + solarCost;
}
else if ((solarPanel = false) || (electric = true))
{
totalPrice = basicPrice + electricCost;
}
else
{
totalPrice = basicPrice;
}
return;
}
public static void totalCost()
{
final int basicPrice = 20000;
final int electricCost = 2000;
final int solarCost = 5000;
final int discountCost = 500;
boolean hybrid = hybridNot();
boolean solarPanel = solarNot();
int finalPrice = 0;
finalPrice = discountNot();
if (finalPrice >= 26500)
{
print("Basic Price: " + basicPrice + "\n" + "Electric model: " + electricCost + "\n" + "Solar Panel: " + solarCost + "\n" + "Discount: " + discountCost);
}
else if (finalPrice >= 25000)
{
print("Basic Price: " + basicPrice + "\n" + "Solar Panel: " + solarCost);
}
else if (finalPrice >= 22000)
{
print("Basic Price: " + basicPrice + "\n" + "Electric model: " + electricCost);
}
else
{
print("Basic Price: " + basicPrice);
}
print("Total: " + finalPrice);
}
由於某些原因,hybridNot和solarNot似乎在轉向下一個方法之前重複自己。對我來說,似乎我可能會在方法結束時返回一個問題,但我實在無法弄清楚什麼是錯誤的。方法totalCost似乎忽略了方法discountNot中的if語句,並且布爾值沒有正確傳遞給totalCost,我只在finalPrice >= 26500
時獲得該值。
再一次,我是一般的Java新手,我也是新來的stackoverflow(所以嗨!!)所以請告訴我,如果我做錯了什麼,我會看看下一次正確的!謝謝!!
我困惑,你說的方法做任何事情,因爲這樣的代碼不實際編譯。你不能在一個聲明瞭返回類型的方法(例如'boolean')中編寫'return'語句,而不用根據你希望返回的值返回'return'。 – RealSkeptic
@RealSkeptic:公平地說,這就是問題所在。但是,當我嘗試實際返回值時,程序變得越來越糟。要麼它開始循環,要麼編譯器抱怨我返回了錯誤的類型。 – Overclock
這意味着存在邏輯問題。這是有道理的,因爲你有三種可能性(電動的,混合的,不好的輸入),但是你選擇了一種只給你兩種可能性的返回類型。你需要改變邏輯(也許把方法裏面的驗證循環?拋出一個異常?) – RealSkeptic