[英]How to get the index of the largest value of three parallel arrays summed together?
[英]How do you remove an elements from three parallel arrays of the same index in java?
我需要讓用戶輸入他們想要刪除的名稱,然后找到數組中的索引,該名稱被保留。 然后我需要刪除名稱以及價格和評級。 我可能只使用並行數組。 我不確定他們的其他部分是否正在成功運行,因為我正在嘗試使用.remove()並且我收到錯誤:
cannot find symbol
symbol: method remove(int)
location: variable array1 of type String[]
碼
public static void removeGames(Scanner keyboard, String[] array1,
double[] array2, double[] array3, int currentLength)
{
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
for(int i = 0; i < array1.length; i++)
{
if(removeInput.equalsIgnoreCase(array1[i]))
{
array1.remove(i);
array2.remove(i);
array3.remove(i);
}
}
}
一些東西。
並行陣列可能會令人困惑。 相反,將所有信息放入其自己的對象中:
class Game { String name; double price, rating; }
然后你可以寫:
ArrayList<Game> games = new ArrayList<Game>();
Array
沒有remove
方法。 您可以使用Arraylist.remove()
方法。
您收到此錯誤的原因是因為Java中的數組對象沒有.remove()
方法。 如果您真的想要一個可以從中刪除對象的動態集合,那么您應該使用ArrayList。
只需用ArrayLists替換方法簽名中的數組,然后在你的體內用array1.get(i)
替換array1[i]
,如下所示:
public static void removeGames(Scanner keyboard, ArrayList<String> array1,
ArrayList<Double> array2, ArrayList<Double> array3, int currentLength) {
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
for(int i = 0; i < array1.length; i++) {
if(removeInput.equalsIgnoreCase(array1.get(i)) {
array1.remove(i);
array2.remove(i);
array3.remove(i);
}
}
}
只需確保導入java.util.ArrayList
。
如果你真的需要使用數組,你應該編寫自己的方法來刪除所需的元素。 由於java在java.util
包中有相當令人印象深刻的容器集合,我建議從那里使用一個。 由於您需要訪問給定索引處的元素,我建議使用ArrayList 。 如果您知道索引並且只想從那里刪除元素,請使用LinkedList 。
我建議也對List接口進行編碼,因此你的代碼看起來像這樣:
public static void removeGames(Scanner keyboard, List<String> array1,
List<Double> array2, List<Double> array3) {
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
int index = array1.indexOf(removeInput);
array1.remove(index);
array2.remove(index);
array3.remove(index);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.