Mik*_*rez -1 java arrays methods
我有个疑问.我正在开发以下代码,它将是您手动引入的数字的多重表.我不能得到的是打印表格.我不知道发生了什么,因为据我所知,所有的代码都是正确的.
public class Tabla
{
public static void main (String[] args)
{
int n=4;
Tabla table = new Tabla ();
int dato [];
dato=table.producto(n);
for (int j=1;j<=10;j++)
{System.out.println(dato[j]);}
}
public int [] producto(int num)
{
int a[]={'0'};
for (int i=1;i<=10;i++)
{a[i]=num*i;}
return a;
}
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗??
提前致谢!
**我将代码更改为:
public class Tabla
{
public static void main (String[] args)
{
int n=4;
int j;
Tabla table = new Tabla ();
int dato[]=new int [10];
dato=table.producto(n);
for (j=0;j<10;j++)
{System.out.println(dato[j]);
}
}
public int [] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
{a[i] = num * (i+1); }
return a;
}
}
Run Code Online (Sandbox Code Playgroud)
奇迹般有效!现在我想知道为什么当我有for循环时编译器抛出"ArrayIndexOutOfBoundsException" for (int i = 1; i <=10; i++)
谢谢您的帮助!:d
根据Wasserman的回答,您应该写的内容如下:
public int[] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
a[i] = num * (i + 1);
return a;
}
Run Code Online (Sandbox Code Playgroud)
您创建了一个单元素数组,而您希望填充一个10元素数组.
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |