对一份文件中的姓名去重后以列表形式输出:
文件内容:
代码实现:
package Array_list_study;
import java.util.*;
import java.io.*;
// 姓名去重
public class Name_de_duplication {
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(new File("name.txt"));
ArrayList<String> list = new ArrayList<String>();
while (input.hasNext()){
String name = input.next();
if(!list.contains(name)){
list.add(name);
}
}
// 对文件中的姓名去重后输出
System.out.println("文件中包含的姓名如下:");
System.out.println("list="+list);
// 对指定姓名进行替换
System.out.println("将姓名Atopos替换为Daisy:");
replace(list,"Atopos","Daisy");
System.out.println("list="+list);
}
public static void replace(ArrayList<String> list,String target,String replacement){
int index = list.indexOf(target); // 获取target在列表中的下标
if (index >= 0){
list.set(index,replacement);
}
}
}
运行结果:
读取一份文件中的单词并删除复数单词
package Array_list_study;
import java.util.*;
import java.io.*;
public class words_read {
public static void main(String[] args) throws FileNotFoundException{
//
ArrayList<String> allWords = new ArrayList<String>();
Scanner input = new Scanner(new File("word_read_data.txt"));
while (input.hasNext()){
String word = input.next();
allWords.add(word);
}
System.out.println(allWords);
// 删去所有复数单词
for(int i = 0;i < allWords.size();i++){
String word = allWords.get(i);
if (word.endsWith("s")){
allWords.remove(i);
i--;
}
}
}
}