如何从arraylist中读取并打印指定范围的元素。 200
packagecom.yichou.assignment;/***sJohnm18tWilliamm42sSusanf18sJackm19sJenniferf28tSop...
package com.yichou.assignment;
/**
* s John m 18
t William m 42
s Susan f 18
s Jack m 19
s Jennifer f 28
t Sophi f 35
t Emma f 37
s Chloe f 14
s Racheal f 14
s Olivia f 20
t Cara f 33
t Tom m 47
s Mia f 21
s Isabella f 18
s Zoe f 21
t Lily f 22
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class people2 {
class person{
String id;
String name;
String gender;
int age;
}
ArrayList<person> allList = new ArrayList<>();
public people2(String filename) throws FileNotFoundException {
readFile(filename);
}
private void readFile(String filename) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(filename));
while(scanner.hasNext()) {
person p = new person();
p.id = scanner.next();
p.name = scanner.next();
p.gender = scanner.next();
p.age = scanner.nextInt();
allList.add(p);
}
}
public void list(int age1,int age2) {//如何完成这个才能方法打印年龄在两个数字之间的名字??
for(int i=0;i<allList.size();i++) {
}
System.out.println();
}
} 展开
/**
* s John m 18
t William m 42
s Susan f 18
s Jack m 19
s Jennifer f 28
t Sophi f 35
t Emma f 37
s Chloe f 14
s Racheal f 14
s Olivia f 20
t Cara f 33
t Tom m 47
s Mia f 21
s Isabella f 18
s Zoe f 21
t Lily f 22
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class people2 {
class person{
String id;
String name;
String gender;
int age;
}
ArrayList<person> allList = new ArrayList<>();
public people2(String filename) throws FileNotFoundException {
readFile(filename);
}
private void readFile(String filename) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(filename));
while(scanner.hasNext()) {
person p = new person();
p.id = scanner.next();
p.name = scanner.next();
p.gender = scanner.next();
p.age = scanner.nextInt();
allList.add(p);
}
}
public void list(int age1,int age2) {//如何完成这个才能方法打印年龄在两个数字之间的名字??
for(int i=0;i<allList.size();i++) {
}
System.out.println();
}
} 展开
1个回答
展开全部
概念上, 透过逐一取出list内的p内容, 去比对符合是否年龄限制.
取法不只一种, 若以for来说, 用index变量i来存取, 可使用indexOf取得第几个元素
然後去比对元素内的年龄, 若符合则印出结果, 若不符合则继续(Continue)下一次回圈
取法不只一种, 若以for来说, 用index变量i来存取, 可使用indexOf取得第几个元素
然後去比对元素内的年龄, 若符合则印出结果, 若不符合则继续(Continue)下一次回圈
追问
老哥,我这样写有什么错吗?
if(p.age!=-1) {
allAgeList.add(p.age);
int temp;
for(int i=0;i=33) {
ageName1.add(p.name);
}
}
}
追答
temp = allAgeList.get(i); // allAgeList?? 跟原题目不一样, 要有宣告才能知道正确与否.
基本上Array放什麼进去就拿什麼出来.
如果放的是person p, 取出就是person p.
temp = allList.get(i);
temp.id
temp.name
temp.gender
temp.age
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询