创建一个WrapperDemo类,它包含一个函数convert2ObjAndStore,它将整数转换为Integer对象,并将Integer对象存储在Vector对象namedintVector中。存储“n”这样的转换对象在intVector中。迭代向量并接收对象作为整数值还包括一个函数,它将一个Integerobject交换到另一个,并在调用例程中显示交换的值(包含在名为WrapperMain的类中的main函数)
我尝试了这个,但是我将错误转换为整数对象
import java.util.*;
class WrapperDemo {
static void Convert(Integer []ob,int n) {
Vector<Integer> store=new Vector<Integer>();
for(int i=0;i<n;i++) {
store.add(ob[i]);
System.out.println(store.get(i));
}
}
}
class WrapperMain {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
int[] x=new int [20];
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n);
}
}
}
答案 0 :(得分:0)
据我所知,您的错误是您将x
声明为int[]
,但将其传递给期望Integer[]
的方法。这不会自动生成!
编辑:为了更清楚......
class WrapperDemo {
static void Convert(Integer []ob,int n) { // <-- type Integer[]
与
int[] x=new int [20]; // <-- type int[] which is NOT equal to Integer[]
// and will NOT be autoboxed to Integer[]
// ...
WrapperDemo.Convert(x,n); // You give type int[] to a method that is expecting Integer[]
作为旁注:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n); // <- You call the convertion in each iteration.
}
在填充循环的每次迭代中调用convertion。所以大多数条目都是null。您可能希望将其更改为:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
}
WrapperDemo.Convert(x,n);