如何在java字符串数组中检查重复的字符串

  • 本文关键字:字符串 数组 java java
  • 更新时间 :
  • 英文 :


我正试图从数组中第一列0中找到重复的值,该列已加载到字符串中并进行拆分,然后在发现时抛出异常。

这是我的密码。

public void loadTrueFalseQuestions() throws Exception {
try {
Scanner input = new Scanner(new FileInputStream(TRUE_FALSE_FILE));
while (input.hasNextLine()) {
line = input.nextLine();
String[] split = line.split(",");
int chapterNumber = Integer.parseInt(split[1]);
String correctAnswer = (split[3]);
String questionID = (split[0]);
if (split.length != TRUE_FALSE_FIELDS) {
throw new Exception();
} else if ((!correctAnswer.matches("TRUE")) & (!correctAnswer.matches("FALSE"))) { //throw new Exception();
} else if (true) {

}
}
} catch (FileNotFoundException e) {
System.out.println("Could not open a file.");
System.exit(0);
}
}

这是CSV文件。

TF001,8,Java allows an instance of an abstract class to be instantiated.,FALSE
TF001,8,Downcasting should be used only in situations where it makes sense.,TRUE
TF003,9,The throw operator causes a change in the flow of control.,TRUE
TF004,9,When an exception is thrown the code in the surrounding try block continues executing 
and then the catch block begins execution.,FALSE

我不知道该怎么做。我无法理解逻辑。我正在尝试一个if语句和contains(questionID(字符串方法,但不确定如何将两者结合起来。(如果有道理的话(。

感谢您的建议。

我使用一个哈希映射,并将键字段作为哈希映射中的键。你可以检查你是否已经把密钥放在散列中,如果是这样,就做点什么,因为你已经有了它。

public void loadTrueFalseQuestions() throws Exception {
try {
Scanner input = new Scanner(new FileInputStream(TRUE_FALSE_FILE));
Map<String, String> myHash = new HashMap<>();
while (input.hasNextLine()) {
line = input.nextLine();
String[] split = line.split(",");
int chapterNumber = Integer.parseInt(split[1]);
String correctAnswer = (split[3]);
String questionID = (split[0]);
if (myHash.containsKey(questionID)) {
// what to do here?
} else {
myHash.put(questionID, line);
}
}
} catch (FileNotFoundException e) {
System.out.println("Could not open a file.");
System.exit(0);
}

}

最新更新