-2

在此示例中,它打印出学生的姓名并将用户从键盘输入的内容记入 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()); 
    }
}
4

4 回答 4

1

您应该/必须使用迭代器,简单的方法是:

Iterator it = pv .iterator();
while(it.hasNext()){
    Student s= it.next();
    if(s.credits>30) System.out.println(s);
}
于 2012-12-12T11:32:30.330 回答
0

您需要使用if 语句。检查 credists 是否大于 30。

if (x > n ) {
 // this block of code will be executed when x is greated then n.
}
于 2012-12-12T11:29:59.423 回答
0

您需要在添加到向量之前进行检查。出于兴趣,您使用向量而不是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));
      } 
 }
于 2012-12-12T11:30:44.090 回答
0

这行得通吗?

if (credits > 30){
    pv.add(new Student(name, credits));
}

代替:

pv.add(new Student(name, credits));
于 2012-12-12T11:30:52.470 回答