比较 2 个数组列表的内容
Comparing contents of 2 array lists
这个程序的目的是导入 2 个文件。一个明文文件和一个字典明文文件。
程序应该搜索文件并比较单词并打印出任何不匹配的单词,即拼写错误的单词。
我已经使用扫描仪通读并将每一行放入一个数组(字典是按行排列的)但是我不知道如何将两个数组列表相互比较。
感谢任何帮助。
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class Dictionary {
public static void main(String[] args) throws FileNotFoundException {
ArrayList <String> words = new ArrayList<String>();
ArrayList <String> dict = new ArrayList<String>();
File inputFile = new File(args [0]);
File inputDictionary = new File(args [1]);
Scanner in = new Scanner(inputFile);
Scanner inDict = new Scanner(inputDictionary);
while(in.hasNext()) {
String word = in.next();
words.add(word);
}
while (inDict.hasNextLine()) {
String correctWord = inDict.nextLine();
dict.add(correctWord);
}
}
}
需要循环遍历words Arraylist中的每一个词,看是否包含在dict Arraylist中
boolean[] misspelled = new boolean[words.size()];
int i = 0;
for (String word : words) {
misspelled[i] = !dict.contains(word);
i++;
}
这定义了一个布尔值数组,用于跟踪所有拼写错误的单词,如果字典列表中不包含特定索引处的单词,则该索引处的布尔值设置为 true,这意味着该单词拼写不正确。
您需要遍历这两个 ArrayList
并比较它们。
for(int i = 0; i<words.size();i++){
for(int j = 0; j<dict.size(); j++){
if(words.get(i).equals(dict.get(j))){
// they are equivalent strings
}else{
// not equivalent
}
}
}
试试这个。
for(String word : words){ //loop for words
if(!dict.contains(word)) //check if dict contain word
System.out.println(word); //print it if dict doesnt have word
}
这个程序的目的是导入 2 个文件。一个明文文件和一个字典明文文件。
程序应该搜索文件并比较单词并打印出任何不匹配的单词,即拼写错误的单词。
我已经使用扫描仪通读并将每一行放入一个数组(字典是按行排列的)但是我不知道如何将两个数组列表相互比较。
感谢任何帮助。
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class Dictionary {
public static void main(String[] args) throws FileNotFoundException {
ArrayList <String> words = new ArrayList<String>();
ArrayList <String> dict = new ArrayList<String>();
File inputFile = new File(args [0]);
File inputDictionary = new File(args [1]);
Scanner in = new Scanner(inputFile);
Scanner inDict = new Scanner(inputDictionary);
while(in.hasNext()) {
String word = in.next();
words.add(word);
}
while (inDict.hasNextLine()) {
String correctWord = inDict.nextLine();
dict.add(correctWord);
}
}
}
需要循环遍历words Arraylist中的每一个词,看是否包含在dict Arraylist中
boolean[] misspelled = new boolean[words.size()];
int i = 0;
for (String word : words) {
misspelled[i] = !dict.contains(word);
i++;
}
这定义了一个布尔值数组,用于跟踪所有拼写错误的单词,如果字典列表中不包含特定索引处的单词,则该索引处的布尔值设置为 true,这意味着该单词拼写不正确。
您需要遍历这两个 ArrayList
并比较它们。
for(int i = 0; i<words.size();i++){
for(int j = 0; j<dict.size(); j++){
if(words.get(i).equals(dict.get(j))){
// they are equivalent strings
}else{
// not equivalent
}
}
}
试试这个。
for(String word : words){ //loop for words
if(!dict.contains(word)) //check if dict contain word
System.out.println(word); //print it if dict doesnt have word
}