谁能告诉我,在构造函数内部使用“ this”构造函数会犯什么错误? 公共Student()。请告诉我如何纠正它。编译器显示此错误-
错误:(10,11)java:构造函数com.shreyansh.Student类中的Student无法应用于给定类型; 必需:无参数 找到:int,java.lang.String 原因:实际和正式论据列表的长度不同
****代码显示在这里****
package com.shreyansh;
import java.util.Scanner;
public class Student {
private int rno;
private String name;
public Student() {
this(0, "Not defined"); //what is the error in this line
}
public void enter() {
System.out.println("Enter name of the student - ");
Scanner scanner = new Scanner(System.in);
this.name=scanner.nextLine();
System.out.println("Enter the roll number - ");
this.rno=scanner.nextInt();
scanner.close();
}
public void show() {
System.out.println("The name of the student is - "+name);
System.out.println("And the roll number is - "+rno);
}
}
答案 0 :(得分:2)
从另一个构造函数调用构造函数时,必须定义要调用的构造函数:
添加此构造函数:
CASE WHEN DATEPART(HOUR, GETDATE()) IN (6,8,10,12) THEN 1 ELSE 0
将允许
public Student(int rno, String name) {
this.rno = rno;
this.name = name;
}
调用以通过编译。
答案 1 :(得分:1)
public Student() {
this(0, "Not defined"); //what is the error in this line
}
尝试执行的操作是使用这些参数在同一类中调用构造函数。为了使其正常工作,该构造函数必须存在:
public Student (int rno, String name) {
this.rno = rno;
this.name = name;
}
但是您没有这样的构造函数,因此将您当前的构造函数更改为:
public Student() {
this.rno = 0;
this.name = "Not defined";
}
或添加第二个构造函数。
答案 2 :(得分:0)
在构造函数内部使用this
时,您正在类中调用另一个构造函数,但是实际上没有其他具有此类参数的构造函数,因此应使用上述参数创建另一个构造函数,例如这个:
public Student(int rno, String name)
{
this.rno = rno;
this.name;
}
答案 3 :(得分:0)
问题在于您创建对象的方式。 您的构造函数必须像:
public Student() {
// you have to indicate the value of each variable here
this.rno = 0;
this.name = "name";
}