2012-12-12 62 views
-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()); 
    } 
} 
+3

使用'if'声明 –

+0

使用GET(.. )来获取值并使用if进行比较。 –

+0

用户可以输入任何字符串作为信用? – BBdev

回答

0

这项工作?

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

代替:

pv.add(new Student(name, credits)); 
+0

然后,应该是一个答案,而不是一个问题。 ;-)。 –

+0

@Vash,什么是失败? ;-) – tiago

+0

是这么简单吗? omg我需要睡觉:)谢谢你 – mehmet

0

您需要使用if statement。检查债权人是否超过30.

if (x > n) { 
// this block of code will be executed when x is greated then n. 
} 
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)); 
     } 
} 
1

你应该/必须使用迭代器,简单的方法来做到这一点是:

Iterator it = pv .iterator(); 
while(it.hasNext()){ 
    Student s= it.next(); 
    if(s.credits>30) System.out.println(s); 
}