Java无法应用于给定类型的字符串和整数

时间:2018-10-11 06:45:58

标签: java arrays string

编译时出现此错误,我不确定为什么得到它或如何解决。

错误是:

RecordEvents3.java:16: error: constructor EventInformation in class EventInformation cannot be applied to given types;
   EventInformation e = new EventInformation("10:53",45);
                        ^
  required: no arguments
  found: String,int
  reason: actual and formal argument lists differ in length
1 error
class RecordEvents3 {
   public static void main (String args[]) {
      Recorder r1 = new Recorder (100,100,"Wombat Detection");
      r1.recordEvent("10:53");
      r1.recordEvent("10:59");
      r1.recordEvent("11:05");
      r1.recordEvent("12:59");
      r1.recordEvent("13:50");
      r1.recordEvent("14:06");
      r1.printEvents();
   EventInformation e = new EventInformation("10:53",45);
      System.out.println("Event recorded at " + e.eventTime +
         ", datum = " + e.eventDatum);
   }
}

class EventInformation {
   public String eventTime;
   public int eventDatum;
}


class Recorder {
   int xPos,yPos;
   String eventType;
   String [] event = new String [6];
   final int EVENT_Max = 10;

   int xevent = 0; 

   Recorder (int xPos, int yPos, String eventType ) {
      this.xPos = xPos;
      this.yPos = yPos ;
      this.eventType = eventType;
   }

   void recordEvent (String eventTime ) {
      event [xevent] = eventTime;
      xevent++;
      if (xevent > 5){
         System.out.println ("Event log overflow - terminating");
         System.exit(1);
      }
   }

   void printEvents(){
      System.out.println ("Record of " + eventType +
            " events at [" + xPos + "," + yPos + "] " );
      int index=0;
      for (String current: event) {
         if (xevent > 5){
            String ss=String.format("Event number %s was recorded at ",index);
            System.out.println(ss + current);
            index++;  
         }
      }      
   }
}

3 个答案:

答案 0 :(得分:4)

您的EventInformation类需要类似

的构造函数
public EventInformation(String eventTime, int eventDatum) {
   this.eventTime = eventTime;
   this.eventDatum = eventDatum;
}

您似乎期望Java构造函数的行为类似于Typescript的行为。初始化字段时,您始终需要显式构造函数。

答案 1 :(得分:2)

您没有为类EventInformation创建带有参数的构造函数,但是您正在代码中使用带参数的构造函数,这就是您的构造函数

class EventInformation {
    public String eventTime;
    public int eventDatum;
}

代替使用

class EventInformation {
    public String eventTime;
    public int eventDatum;

    EventInformation(String eventTime, int eventDatum) {
        this.eventTime=eventTime;
        this.eventDatum=eventDatum;
    }
}

答案 2 :(得分:1)

您需要使用相应的参数指定构造器。 如果您的类中没有指定构造函数,则将创建不带参数的默认构造函数,并使用null初始化您的字段引用。