首页 > 解决方案 > 如何在java中的方法中打印实例变量?

问题描述

我正在尝试在 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();
    }
}

标签: javaclassobjectconstructorparameter-passing

解决方案


在通过扫描仪分配它们之前,您正在为 s 和 i 分配值。

 test(String name, int id) {
        Scanner sc = new Scanner(System.in);

        System.out.print("enter Name:");
        name = sc.nextLine();
        s = name;

        System.out.print("enter id:");
        id = sc.nextInt();
        i = id;
    }

推荐阅读