gpt4 book ai didi

java - 文件输出时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:55 25 4
gpt4 key购买 nike

我希望能够从文件中读取 20 个随机名称并将它们放入一个新文件中。我该怎么办?

public class Assignment2 {

public static void main(String[] args) throws IOException
{
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
//BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
List<String> lines = new ArrayList<String>();

String line = reader.readLine();

while( line != null ) {
lines.add(line);
line = reader.readLine();
}

// Choose a random one from the list
Random r = new Random();

for (int i = 0; i < 20; i++)
{
int rowNum = r.nextInt(lines.size ());
System.out.println(lines.get(rowNum));
}

}
}

最佳答案

try (BufferedWriter writer = new BufferedWriter(new FileWriter("randomNames.txt"))) {

Random random = new Random();

for (int i = 0; i < 20; i++) {
int rowNum = random.nextInt(lines.size());
writer.write(lines.get(rowNum));
writer.newLine();
}
}

如果您需要检查某个号码是否已被使用,请将其添加到集合中:

try (BufferedWriter writer = new BufferedWriter(new FileWriter("randomNames.txt"))) {
Set<Integer> usedNumbers = new HashSet<Integer>(20);
Random random = new Random();
int addedCount = 0;

while (addedCount < 20) {
int rowNum = random.nextInt(lines.size());
if (usedNumbers.add(rowNum)) {
writer.write(lines.get(rowNum));
writer.newLine();
addedCount++;
}
}
}

检查是否有另一个名称具有相同的第一个字符:

private static void containsNameWithSameFirstCharacter(Collection<String> names, String name) {
for (String anotherName : names) {
if (anotherName.charAt(0) == name.charAt(0)) {
return true;
}
}
return false;
}

然后你就可以:

    Random random = new Random();
Set<String> usedNames = new HashSet<String>(20);

while (usedNames.size() < 20) {
int rowNum = random.nextInt(lines.size());
String name = lines.get(rowNum);
if (!containsNameWithSameFirstCharacter(usedNames, name)) {
usedNames.add(name);
writer.write(name);
writer.newLine();
}
}

关于java - 文件输出时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35323180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com