2012-12-12 60 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); 
}