show () 메서드에서 변수를 인쇄하려고합니다. 그러나 매번 그것은 문자열 NULL 및 정수 0과 같은 기본값을 표시합니다. 매개 변수화 생성자를 가져 왔습니다. 대신 클래스의 객체를 생성 할 때 인수를 전달해야하므로 해당 변수의 값을 사용자로부터 전달할 변수를 전달하고 싶지만 수행 할 수 없습니다.
import java.util.*;
public class Cons_With_Arg {
String s;
int i;
// Scanner sc=new Scanner(System.in);
Cons_With_Arg(String name, int id) {
Scanner sc = new Scanner(System.in);
this.s = name;
System.out.print("enter Name:");
name = sc.nextLine();
this.i = id;
System.out.print("enter id:");
id = sc.nextInt();
}
public void show() {
System.out.println("Name:" + this.s);
System.out.println("Id:" + this.i);
}
public static void main(String[] args) {
Cons_With_Arg co = new Cons_With_Arg(s, i);
// System.out.println("Name:" + co.s);
// System.out.println("Id:" + co.i);
co.show();
}
}
생성자에서 값을 읽어서는 안됩니다.
먼저 읽어보세요
public static void main(String[] args) {
String s;
int i;
Scanner sc = new Scanner(System.in);
System.out.print("enter Name:");
s = sc.nextLine();
System.out.print("enter id:");
i = sc.nextInt();
Cons_With_Arg co = new Cons_With_Arg(s, i);
co.show();
}
그런 다음 클래스 생성자에서 사용하십시오.
Cons_With_Arg(String name, int id) {
this.s = name;
this.i = id;
}
이제 모든 것이 작동합니다.
enter Name:a
enter id:1
Name:a
Id:1
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다