gpt4 book ai didi

Java 方法从 ArrayList 中查找以给定字符串开头的名称变量

转载 作者:行者123 更新时间:2023-11-30 02:38:14 25 4
gpt4 key购买 nike

我制作了一个 ArrayList.txt,其中包含学生及其成绩的列表,一个单独的类(class)学生包含 getName()getGrade() getMarks() 等,在我的主类上,我有一个将从该方法中提取的主方法

因此我的方法如下:

public static String findName(ArrayList<Student> o, String name) {

for(int i = 0; i < o.size(); i++)
{
if(o.get(i).getName().startsWith(name.toLowerCase()))
System.out.print(o.get(i));
}
return name;
}

我的主要方法有这个findName(students, "al");

我的 array.txt 看起来像这样

afafwafa
B
80
alicegg
C
70
lfhif
D
50
Allllleeee
A
94

但是,即使我的所有其他方法都正常工作,我的 findName() 方法无法提取所有以“al”开头的名称。另外我需要注意该方法应该不区分大小写,并且我需要使用 .startsWith()。有什么建议吗?

要补充的是,对于给定的带有字符串文件名的 Student 类型的 ArrayList,我需要创建一个方法,该方法将使用 Student 将 arraylist 的成员写入具有给定名称的文本文件,其中使用 Student 将 1 个元素写入一行类 toString 方法格式。我需要用 try/catch 处理可能的异常。我还需要在代码中使用 filereader、fileoutputsteam、printwriter、printstream

public static void nameToFile(ArrayList<Student> a, String file) {      

int i = inone.read();
FileReader inone = new FileReader(a.get(i).toString());
FileOutputStream fos = new FileOutputStream(file);
PrintWriter outone = new PrintWriter(fos);

outone.close();
}

我的主要方法有这个

nameToFile(students2,"modified.txt");

最佳答案

Also i need to take note that the method should be case insensitive and i need to use .startsWith().

如果您希望 startsWith() 方法忽略大小写,只需在比较之前将两者转换为小写或大写即可:

if(o.get(i).getName().toLowerCase().startsWith(name.toLowerCase()))

如果您的 findName() 应该只返回 1 个名称,您可以在 if 条件中返回它。如果要返回名称列表,请将其添加到另一个数组列表,然后返回该数组列表。

关于Java 方法从 ArrayList 中查找以给定字符串开头的名称变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516656/

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