java - 我在使用这个构造函数时遇到问题

标签 java constructor

谁能告诉我,我在构造函数内部使用“this”构造函数时犯了什么错误 公共(public)学生()。请告诉我如何纠正它。编译器显示此错误 -

错误:(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);
      }
}

最佳答案

当您从另一个构造函数调用一个构造函数时,您必须定义您正在调用的构造函数:

添加此构造函数:

public Student(int rno, String name) {
    this.rno = rno;
    this.name = name;
}

将允许

this(0, "Not defined");

调用以传递编译。

关于java - 我在使用这个构造函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61246068/

相关文章:

java - 如何从 ArrayList<Map<String, String>> 创建 JSON 对象?

javascript - 对象构造函数作为大对象中的函数

c++ - 模板对象声明和初始化: manually call template constructor to bypass standard constructors calls order

javascript - 创建 JS 对象的最优化方式

c++ - 结构默认构造函数 : will it initialize my members with default vaues i. e。 'zeros'

java - 我的索引参数不起作用

java - Gradle 不会自动发现 JPA 实体类

java - 在字段之前和 getter 声明之前使用 @XmlElement 有什么区别?

java - 从两个数据库同步获取结果

c# - 使用base()有意义吗?