【发布时间】:2021-04-16 03:40:53
【问题描述】:
我正在尝试在 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();
}
}
【问题讨论】:
-
您更新了错误的字段。您可以尝试更改 name = sc.nextLine(); to this.s= sc.nextLine();
标签: java class object constructor parameter-passing