嗨,大家好!=) 我是 Java 新手,目前我正在學習陣列和回圈。我有一個有趣的家庭作業,我很困惑。我不知道該怎么處理這個。所以我需要你的建議。
在其中創建一個公共 String getCheapStocks(String[] stock) 方法。它需要一個字串陣列作為輸入。每行由產品名稱及其價格組成,由一個空格分隔。
該方法回傳一個字串 - 價格低于 200 的產品名稱串列。 getCheapStocks(new String[] {"gun 500", "firebow 70", "pixboom 200"}) 回傳“firebow”。
只有for回圈可以使用。
我找到了一種可以拆分字串的方法:
字串文本 = "123 456"
String[] 部分 = text.split(" ")
int number1 = Integer.parseInt(parts[0]) //123
int number2 = Integer.parseInt(parts[1]) //456
但是當我有字串“gun 500”時,我只能將它分成兩個字串。而且我無法將它與 200 進行比較。我的代碼一團糟,它什么也沒做。
我非常感謝任何提示或建議,在此先感謝!
public static String getCheapStocks(String[] stocks) {
//MESS!
int max = 200;
for(int i = 0; i < stocks.length; i ) {
String txt = stocks[i];
String[] parts = txt.split(" ");
int number1 = Integer.parseInt(parts[0]);
int number2 = Integer.parseInt(parts[1]);
if(number1 < max) {
}
}
}
public static void main(String[] args) {
//returns "firebow"
System.out.println(getCheapStocks(new String[] {"gun 500", "firebow 70", "pixboom 200"}));
}
}
uj5u.com熱心網友回復:
由于您的輸入格式為"<stock> <price>",因此將其拆分為 2 部分后,您只需將第二部分轉換為整數,否則會出現例外。
public static String getCheapStocks(String[] stocks) {
// Use a StringBuilder to hold the final result
StringBuilder result = new StringBuilder();
for (String stock : stocks) {
String[] parts = stock.split(" ");
// If the price is lower than 200, append part[0] (stock name) to the result
if (Integer.parseInt(parts[1]) < 200) {
result.append(parts[0]).append(" "); // Append also a space character for dividing the stocks
}
}
// Strip the space from the end
return result.toString().trim();
}
uj5u.com熱心網友回復:
public static String getCheapStocks(String[] stocks) {
int maxPrice = 200;
List<String> results = new ArrayList<>();
for (String txt : stocks) {
String[] parts = txt.split(" ");
String stockName = parts[0];
int price = Integer.parseInt(parts[1]);
if (price < maxPrice) {
results.add(stockName);
}
}
return String.join(" ", results);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465265.html
下一篇:計算范圍內包含的陣列價格的總和
