使用数组Java中的每个对象打印语句

时间:2017-09-24 22:06:01

标签: java arrays loops for-loop printing

在增强型for循环中,我似乎无法打印每个对象。任何援助将不胜感激。如果我选择了一个特定的工作对象,那么代码运行正常,但我只是将它作为worker []。fullName()并且没有任何内容正在打印。有没有办法可以让它在每次循环循环时打印相应的工作人员?感谢

package Persons;

public class InheritanceTest {
    public static void main(String[] args) {
         Workers worker[] = new Workers[6];
         worker[0] = new Workers(25,"Tom", "Atkins", "4", "Mr.", 1992 );
         worker[1] = new Workers(28,"John", "Smith", "5", "Mr.", 1993 );
         worker[2] = new Workers(30,"Joe", "Doe", "6", "Mr.", 1980 );
         worker[3] = new SalaryWorker(50000,"Fawn", "Dawn", "7", "Mrs.", 1994 );
         worker[4] = new SalaryWorker(55000,"Clarence", "West", "8", "Mr.", 1986 );
         worker[5] = new SalaryWorker(60000,"Lucy", "Adams", "9", "Ms.", 1979 );

         for (Workers workers: worker){
             System.out.println("Week 1 pay period: "+ worker[].fullName());
             workers.calculateWeeklyPay(40);
             System.out.println("Week 2 pay period: ");
             workers.calculateWeeklyPay(50);
             System.out.println("Week 3 pay period: ");
             workers.calculateWeeklyPay(40);            
         }        
    }
}

1 个答案:

答案 0 :(得分:1)

认为在for-each循环中命名有问题。你已经互换了worker& workersworker[].fullName()也是不可接受的结构。正确是worker.fullName() 请尝试以下代码:

for (Workers worker : workers) {
        System.out.println("Week 1 pay period: " + worker.fullName());
        worker.calculateWeeklyPay(40);
        System.out.println("Week 2 pay period: ");
        worker.calculateWeeklyPay(50);
        System.out.println("Week 3 pay period: ");
        worker.calculateWeeklyPay(40);
}