Java根据标题查找ID函数调用问题:索引参数无法确定
findIdByTitle函数的问题 Hey there! Let's work through this issue so you can get your function up and running smoothly. The core problem here is that you can't hardcode an index for getGradeList().get(****?****) because you don't know which grade entry contains the title you're searching for. Here's how to fix this:
问题分析
Your findIdByTitle function is built to search through two parallel lists (IDs and Titles), but right now you're trying to target a single grade entry directly. Since you don't know which grade holds your target title, you need to loop through every grade in the grade list and check each one's title set.
解决方案1:遍历Grade列表调用原函数
Keep your existing findIdByTitle function, and adjust your call logic to iterate over all grades in getGradeList():
// Define the title you're looking for String targetTitle = "The Title You Need"; int foundId = 0; // Using 0 as your "no match" marker // Get the full list of grades List<Grade> gradeList = Core.userSignIn.getBasicList().getGradeList(); // Check each grade's titles for a match for (Grade grade : gradeList) { int tempId = findIdByTitle(grade.getID(), grade.getTitles(), targetTitle); if (tempId != 0) { foundId = tempId; break; // Stop searching once we find a match (remove this line if you need all matches) } } // Use foundId for your logic now
Note: Replace Grade with the actual class type of elements in getGradeList() if it's different.
解决方案2:重构函数以直接处理Grade列表
For cleaner, more concise code, you can rewrite the function to accept the full grade list directly—no need to handle the loop outside:
public static int findIdByTitleInGrades(List<Grade> gradeList, String title) { for (Grade grade : gradeList) { List<Integer> gradeIds = grade.getID(); List<String> gradeTitles = grade.getTitles(); for (int i = 0; i < gradeIds.size(); i++) { // Use equalsIgnoreCase instead of equals if you need case-insensitive matching if (gradeTitles.get(i).equals(title)) { return gradeIds.get(i); } } } return 0; // Return 0 if no matching title is found }
Then call it with a single line:
String targetTitle = "Your Target Title"; int id = findIdByTitleInGrades(Core.userSignIn.getBasicList().getGradeList(), targetTitle);
额外优化建议
- Case sensitivity: If you want to match titles regardless of uppercase/lowercase, swap
equals(title)withequalsIgnoreCase(title). - "No match" marker: Returning
0could cause confusion if0is a valid ID. Consider returningIntegerinstead ofint, so you can returnnullwhen no match is found. - Multiple matches: The current functions return the first matching ID. If you need all matching IDs, modify the function to return a
List<Integer>instead of a singleint.
内容的提问来源于stack exchange,提问作者Shahriyar Aghajani

