我想要一种从键盘读取数字的返回类型方法。所以我创建了这个方法。但它不会返回任何东西。我的代码中有什么问题?
int num [] = new int[10];
public int read()
{
Scanner s=new Scanner(System.in);
for(i=0;i<num.length;i++)
{
System.out.println("Enter the number "+i);
num[i] = s.nextInt();
}
return num;
}
答案 0 :(得分:2)
如果要返回数组,请将返回类型更改为int[]
。
在方法中创建数组也会更好,因为您可能不希望在连续调用中返回相同的数组对象。
public int[] read()
{
int num [] = new int[10];
Scanner s=new Scanner(System.in);
for(i=0;i<num.length;i++)
{
System.out.println("Enter the number "+i);
num[i] = s.nextInt();
}
return num;
}