使用Java中的参数化构造函数创建对象时出错

Tam*_*was 0 java oop class object

在创建对象和参数化构造函数时,我遇到了以下错误.

Main.java:6:错误:构造函数类Cipher中的密码不能应用于给定的类型

Cipher cy = new Cipher(k);              ^
Run Code Online (Sandbox Code Playgroud)

必需:没有参数

发现:int

原因:实际和正式的参数列表长度不同

这是我的文件看起来像

<b>Main.java</b>

public class Main {
    public static void main(String []args){
   int k=8;
      Cipher cy = new Cipher(k);
      String encrypted_msg = cy.encrypt(message);
      String decrypted_msg = cy.decrypt(encrypted_msg);
      view1.displayResult("Decrypted message: "+decrypted_msg);
        }
    }

<b>Cipher.java</b>

import java.util.*;
public class Cipher
    {
    private int key;
    // Constructor 
    public void Cipher(int k)
        {
        key = k; 
        }// end Constructor 

    } // end class 
Run Code Online (Sandbox Code Playgroud)

EJK*_*EJK 7

更改

public void Cipher(int k)
Run Code Online (Sandbox Code Playgroud)

public Cipher(int k)
Run Code Online (Sandbox Code Playgroud)

返回类型为void,不是构造函数.在Java中,构造函数不指定返回类型.返回类型只是类的名称.

因此,在您的示例中,由于您尚未定义构造函数,因此Java将提供以下格式的默认无参数构造函数:

public Cipher() {}
Run Code Online (Sandbox Code Playgroud)

因此,错误消息告诉您只存在无参数构造函数,但您正在调用需要int参数的构造函数.