我在第 5 行收到一条错误消息,指出无法从 String 转换为 int。该问题要求我使用 size 参数实例化名称数组。我该如何纠正它?
class ProgClass{
private String name[];
public ProgClass(int size){
this.name = new int[size];
}
然后,我想通过询问用户输入来搜索索引:
int cnt = cnt.nextInt
System.out.println("Name "+cnt+" is " + name[cnt-1]);
有什么办法可以做到吗?
最佳答案
您已将其声明为 String 数组,但随后将其分配给新的 int 数组。
this.name = new String[size];
这对我来说看起来像是一个错字。但问题来自于这样一个事实:大小参数是您希望字符串数组的整数大小。但它已被编码为,使我的 String 数组现在等于一个新的 int 数组,该数组具有我传递到该方法中的大小。这不是你想要的。
关于java - 使用大小参数实例化名称数组的公共(public)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209528/