在此示例中,它会打印出学生的姓名,并将用户从键盘输入的内容记入 Vector。
但我只想打印出学分超过 30 的矢量。
感谢您的任何帮助。
public class Main {
public static void main(String[] args) {
Teacher t = new Teacher("Prof. Smith", "F020");
Student s = new Student("Gipsz Jakab", 34);
Vector<Person> pv = new Vector<Person>();
pv.add(t);
pv.add(s);
Scanner sc = new Scanner(System.in);
String name;
int credits;
for (int i=0;i<5;i++){
System.out.print("Name: ");
name = sc.nextLine();
System.out.print("Credits: ");
credits = sc.nextInt();
sc.skip("n");
pv.add(new Student(name, credits));
}
System.out.println(pv);
System.out.println("The size of the Vector is: " + pv.size());
}
}
你应该/必须使用迭代器,最简单的方法是:
Iterator it = pv .iterator();
while(it.hasNext()){
Student s= it.next();
if(s.credits>30) System.out.println(s);
}
这行得通吗?
if (credits > 30){
pv.add(new Student(name, credits));
}
而不是:
pv.add(new Student(name, credits));
你需要使用 if 语句。检查可信度是否大于 30。
if (x > n ) {
// this block of code will be executed when x is greated then n.
}
在添加到向量之前,您需要检查一下。出于兴趣,您使用的是向量而不是 ArrayList 的任何原因
for (int i=0;i<5;i++){
System.out.print("Name: ");
name = sc.nextLine();
System.out.print("Credits: ");
credits = sc.nextInt();
sc.skip("n");
if (credits >= 30) { //this additional check is needed
pv.add(new Student(name, credits));
}
}