0

I'm getting below error when creating object along with parameterized constructor.

Main.java:6: error: constructor Cipher in class Cipher cannot be applied to given types

Cipher cy = new Cipher(k);              ^

required: no arguments

found: int

reason: actual and formal argument lists differ in length

Here is my files looks like

<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 

2 Answers 2

8

Change

public void Cipher(int k)

to

public Cipher(int k)

With a return type of void, that is not a constructor. In Java, a constructor does not specify a return type. The return type is simply the name of the class.

So in your example, because you have not defined a constructor, Java will provide a default no-argument constructor of the following format:

public Cipher() {}

thus the error message is telling you that only a no-argument constructor exists, but you are calling a constructor that expects an int argument.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It did worked pretty well. I'm not a frequent user of Java. But this looks quite interesting. Java is a piece of work. Thanks again.
1
<b>Cipher.java</b>

import java.util.*;
public class Cipher
    {
    private int key;
    public Cipher(int k) //remove the void
        {
        this.key = k; //use this for object level reference
        } 

    }

2 Comments

Please add some text as to how your post answers the question, and what the original author can do. Thank you.
Thanks for the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.