我是 Java 新手,目前我正在學習陣列和回圈。我的家庭作業中有一個有趣的任務。
撰寫一個程式,將通過的每個價格相乘:
如果商品價格低于 1000,則為 2。如果商品價格大于或等于 1000,則為 1.5。
任務:
寫方法public void multiple prices (float [] prices)。它需要一個價格陣列,如果價格小于 1000,則將每個價格乘以 2,如果價格大于或等于 1000,則乘以 1.5。
測驗示例:
multiplyPrices()使用資料呼叫[100, 1500]應該將傳輸的陣列更改為[200, 2250].
在這里我被卡住了=(
我寫了一個代碼,它接受一個陣列,將它轉換為浮點數,取它的值,并用 if-else 陳述句檢查它,唯一的問題是我不知道如何把它放回去。
我的同學說看起來好像我計算了正確的值并立即將它們顯示在控制臺中,而無需更改價格陣列的資料。最后的程式顯示了陣列的值,這就是我得到這樣一個結果的原因。有必要不要列印x1到x3控制臺,我需要保存x1并保存x3在 index 下的一組價格中i。然后,在檢查任務時,應顯示“正確”。
但這怎么能做到呢?不幸的是,如果使用 if-else,資料既不能向后提取,也不能向前提取。
你能給點建議嗎?
先感謝您!
import java.util.Arrays;
public class QuadraticEquationSolver {
public void multiplyPrices(float[] prices) {
for (int i = 0; i < prices.length; i ) {
float season = prices[i];
if (season >= 1000) {
float x1 = season * 1.5f;
float x2 [] = new float[] {x1};
System.out.print(Arrays.toString(x2));
} else if (season < 1000 ) {
float x3 = season * 2f;
float x4 [] = new float[] {x3};
System.out.print(Arrays.toString(x4));
}
}
}
public static void main(String[] args) {
QuadraticEquationSolver shop = new QuadraticEquationSolver();
//Should be [200, 2250]
float[] prices = new float[] {100f, 1500f};
shop.multiplyPrices(prices);
System.out.println(Arrays.toString(prices));
}
}
uj5u.com熱心網友回復:
試試下面的代碼:
import java.util.Arrays;
public class QuadraticEquationSolver {
public void multiplyPrices(float[] prices) {
for (int i = 0; i < prices.length; i ) {
if (prices[i] < 1000)
prices[i] = prices[i] * 2;
else
prices[i] = (float) (prices[i] * 1.5);
}
}
public static void main(String[] args) {
QuadraticEquationSolver shop = new QuadraticEquationSolver();
//Should be [200, 2250]
float[] prices = new float[] {100f, 1500f};
shop.multiplyPrices(prices);
System.out.println(Arrays.toString(prices));
}
}
在此處閱讀有關 java 陣列的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460386.html
