[英]Java method to find a name variable starting with a given string from an ArrayList
I have made an ArrayList.txt which contains a list of students with their grades, a separate class student containing getName()
, getGrade()
, getMarks()
etc and on my main class, I have a main method which will pull from this method 我制作了一个ArrayList.txt文件,其中包含学生的成绩列表,一个单独的班级学生,其中包含
getName()
, getGrade()
, getMarks()
等,在我的主类中,我有一个main方法可以从中获取方法
Hence my method goes as this: 因此,我的方法如下:
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;
}
and my main method has this findName(students, "al");
而我的主要方法有这个
findName(students, "al");
my array.txt looks something like this 我的array.txt看起来像这样
afafwafa
B
80
alicegg
C
70
lfhif
D
50
Allllleeee
A
94
however my findName()
method is unable to pull all names that starts with "al" even though all my other methods are working. 但是,即使我所有其他方法都在工作,我的
findName()
方法也无法提取以“ al”开头的所有名称。 Also I need to take note that the method should be case insensitive and i need to use .startsWith()
. 我还需要注意,该方法应不区分大小写,并且我需要使用
.startsWith()
。 Any suggestions? 有什么建议么?
To add on, with the given ArrayList of type student with a string file name, i need to create a method that will write the members of the arraylist to a text file with a given name with 1 element to a line using student class toString method format. 要添加,使用具有字符串文件名的Student类型的给定ArrayList,我需要创建一个方法,该方法将使用学生类toString方法将arraylist的成员写入具有给定名称的文本文件,其中具有1个元素的一行格式。 i need to handle possible exceptions with try/catch.
我需要使用try / catch处理可能的异常。 I also need to use either filereader, fileoutputsteam, printwriter, printstream in the code
我还需要在代码中使用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();
}
my main method has this 我的主要方法有这个
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 you want your startsWith()
method to ignore the case, just convert both to lower or upper case before comparison: 如果您希望
startsWith()
方法忽略大小写,只需在比较之前将大小写都转换为小写或大写即可:
if(o.get(i).getName().toLowerCase().startsWith(name.toLowerCase()))
If your findName()
is supposed to just return 1 name, you can return it in the if-condition. 如果您的
findName()
仅返回1个名称,则可以在if条件中返回它。 If you want to return a list of names, add it to another arraylist, then return the arraylist. 如果要返回名称列表,请将其添加到另一个arraylist中,然后返回该arraylist。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.