主类无法识别Liber类?无参构造缺失报错求助
Hey there! Let's work through your two issues step by step:
Issue 1: Missing no-argument constructor
The error about needing Liber() happens because once you define a custom constructor (your Liber(int i, String T, int VP)), Java stops providing the default no-argument constructor automatically. When you try to create an instance with new Liber();, the compiler can't find that constructor.
Fix options:
Add a no-argument constructor to the Liber class
This lets you usenew Liber()as you originally tried. Also, I noticed a bug in your existing constructor—you're assigning the parameterTto the member variableTitullibackwards! Correct that too:package tipetnumerike; public class Liber { private int id; private String Titulli; private int VitiPublikimit; // Add no-argument constructor public Liber() { // Optional: Set default values if needed, e.g. // this.id = 0; // this.Titulli = ""; // this.VitiPublikimit = 0; } public Liber(int i, String T, int VP) { id = i; VitiPublikimit = VP; Titulli = T; // Fixed the assignment direction here } // Complete the getId method public int getId() { return id; } }Use your existing parameterized constructor
If you don't need a no-argument constructor, pass the required values when creating the instance:// In your main method Liber l = new Liber(1, "My Book Title", 2023);
Issue 2: Main class can't recognize the Liber class
This usually comes down to package structure or imports. Here's how to fix it:
If your main class is in the same package (tipetnumerike)
- Make sure both
Main.javaandLiber.javaare in the same directory (e.g.,src/tipetnumerike/). - Add the package declaration at the top of your main class:
package tipetnumerike; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); Liber l = new Liber(); // Now this should work } }
If your main class is in a different package
- Add an import statement for the Liber class at the top of your main class:
import tipetnumerike.Liber; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); Liber l = new Liber(); } } - Also ensure your directory structure matches the package names (e.g.,
tipetnumerike/folder containingLiber.java, and your main class in its own folder or root).
Compilation/Runtime tip
If you're compiling from the command line, make sure to compile all files in the package:
javac tipetnumerike/*.java
Then run the main class using its fully qualified name:
java tipetnumerike.Main
内容的提问来源于stack exchange,提问作者alison

