簡體   English   中英

我在使用這個構造函數時遇到問題

[英]I am facing problem in using this constructor

誰能告訴我,我在構造函數 public Student() 中使用“this”構造函數時犯了什么錯誤。 請告訴我如何糾正它。 編譯器顯示此錯誤 -

錯誤:(10, 11) java: class com.shreyansh.Student 中的構造函數 Student 不能應用於給定類型; 必需:未找到 arguments: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");

調用通過編譯。

public Student() {
          this(0, "Not defined"); //what is the error in this line
      }

嘗試做的是使用這些參數在同一個 class 中調用構造函數。 為了讓它工作,這個構造函數必須在那里:

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

但是您沒有這樣的構造函數,因此將當前的構造函數更改為:

public Student() {
  this.rno = 0;
  this.name = "Not defined";
}

或者,添加第二個構造函數。

當您在構造函數中使用this時,您正在調用 class 中的另一個構造函數,但實際上您沒有任何其他具有此類 arguments 的構造函數,因此您應該創建另一個具有上述參數的構造函數,如下所示:

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

問題是您創建 object 的方式。 你的構造函數必須像:

public Student() {
       // you have to indicate the value of each variable here
      this.rno = 0; 
      this.name = "name";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM