3 回答

TA貢獻1880條經(jīng)驗 獲得超4個贊
您的方法似乎有一些邏輯和編譯問題。
看起來你需要這個方法,
public static List<Integer> questionMissed(String[] user, String[] test) {
List<Integer> qMissed = new ArrayList<Integer>();
for (int i = 0; i < user.length; i++) {
if (!user[i].equals(test[i])) {
qMissed.add(i);
}
}
return qMissed.size() == 0 ? null : qMissed;
}
修復(fù)和他們的解釋,
1. Your return type has to be List<Integer> instead of ArrayList<String> because you want to return an ArrayList of Integer indexes and not string.
2. Second problem you can't use primitive type in ArrayList<int> instead you need to use ArrayList<Integer>
3. You can't compare strings with == instead you need to use equals method on string.
4. You don't have to return null inside forloop else hence else block I have removed.
5. After you exit the forloop, as you want to return null if both element's arrays matched hence this code,
return qMissed.size() == 0 ? null : qMissed;
如果您在使用此方法時遇到任何問題,請告訴我。
編輯:
如果兩個傳遞的數(shù)組具有相同的數(shù)字,如何顯示“全部正確”消息。你一定是這樣稱呼它的,
List<Integer> list = questionMissed(user,test);
if (list == null) {
System.out.println("All are correct");
} else {
// your current code
}

TA貢獻1830條經(jīng)驗 獲得超3個贊
您可以嘗試在方法中將返回類型從 ArrayList 更改為 ArrayList:
public static ArrayList<int> questionMissed(String[] user, String[] test) {
ArrayList<int> qMissed = new ArrayList<int>();
for (int i=0;i<=user.length-1;i++) {
if (user[i] != test[i]) {
qMissed = Arrays.asList(qMissed).indexOf(user);(i+1);
} else {
return null;
}
}
return qMissed;
}
如果條件原因是多余的,您也可以刪除 else。請附上您得到的例外情況。

TA貢獻1875條經(jīng)驗 獲得超5個贊
我看到您的代碼存在多個問題,首先,正如 Andreas 所說 ArrayList 無法承載原始類型,因此將其更改為
ArrayList<Integer> qMissed = new ArrayList<Integer>();
我看到的第二個問題是,您使用==此比較比較字符串可能是錯誤的,因此請equals改用
(user[i].equals(test[i]))
我看到的最后一個錯誤是代碼無法編譯,你能否在評論中給我更多信息,說明你在這部分嘗試做的事情,因為它不是有效的代碼
qMissed = Arrays.asList(qMissed).indexOf(user);
(i + 1);
如果你想做類似 Pushpesh Kumar Rajwanshi 回答的事情,你可以使用 java 8 流,它的作用是創(chuàng)建一個具有用戶長度的 IntStream,然后過濾它以僅包含在相同索引處不相等的項目,然后將其添加到qMissed.
public static List<Integer> questionMissed(String[] user, String[] test) {
List<Integer> qMissed = new ArrayList<>();
IntStream.range(0, user.length)
.filter(i -> !user[i].equals(test[i]))
.forEach(qMissed::add);
return qMissed.size() == 0 ? null : qMissed;
}
添加回答
舉報