在此示例中,它打印出学生的姓名,并将用户从键盘输入的内容归功于Vector。
但我只想打印出信用额度超过30的Vector。
感谢您的帮助。
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());
}
}
答案 0 :(得分:1)
你应该/必须使用迭代器,简单的方法是:
Iterator it = pv .iterator();
while(it.hasNext()){
Student s= it.next();
if(s.credits>30) System.out.println(s);
}
答案 1 :(得分:0)
您需要使用if statement。检查信用卡是否大于30.
if (x > n ) {
// this block of code will be executed when x is greated then n.
}
答案 2 :(得分: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));
}
}
答案 3 :(得分:0)
这会有用吗?
if (credits > 30){
pv.add(new Student(name, credits));
}
而不是:
pv.add(new Student(name, credits));