java - 如何在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();
}
}
解决方案
在通过扫描仪分配它们之前,您正在为 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;
}
推荐阅读
- python - exchangelib 会议从房间电子邮件中获取日历
- django - 获取和插入 Django 在 Angular 中设置的 CSRF cookie 的值
- swift - 无法从不同的 VC Swift 获取 switch 的值
- azure - New-AzureStorageContainer :远程服务器返回错误:(403)在PowerShell中禁止
- java - ExpressionEvaluatingRequestHandlerAdvice Spring 集成
- visual-studio - 如何在 Visual Studio 2017 中以编程方式运行静态代码分析?
- jose4j - 签名 JWT 和 JWK 之间的 jose4j 算法不匹配
- postgresql - 简单的字符串返回函数,默认参数为 NULL,返回 NULL 而不是字符串
- javascript - javascript试图生成一个数组,该数组每x个条目推送一次空白条目
- javascript - 在 React 中使用 js 创建 html 块