运行环境Java11,eclipse
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = sc.nextInt();
int b[] = new int[n];
int c = (int) Math.pow(10, n - 1);
int f[] = new int[n];
for (int i = 0; i < Math.pow(10, n); i++) {
int d = i;
for (int j = 0; j < b.length; j++) {
c = (int) Math.pow(10, n - 1 - j);
b[j] = d / c;
f[j] = d / c;
d = d - b[j] * c;
}
int t = n;
int s[] = null;
for (int l = 0; l < n - 1; l++) {
s = new int[t - 1];
for (int j = 0; j < s.length; j++) {
s[j] = b[j] + b[j + 1];
}
b = new int[t - 1];
for (int j = 0; j < s.length; j++) {
b[j] = s[j];
}
t--;
}
if (s[0] == sum) {
for (int j = 0; j < f.length - 1; j++) {
System.out.print(f[j] + " ");
}
System.out.println(f[f.length - 1]);
break;
}
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at cn.lqb.lianxi.Shuziyouxi.main(Shuziyouxi.java:31)
错误是上面代码第25行
分成两部分都能正常运行
温馨提示:学会使用debug你不吃亏
idea和eclipse都有,你通过启动debug来排查不很快就明白了吗?
我输入的数据是 3 4
t影响了b,请问导致b数组只有b[0],哪来的b[1]?所以b[j+1]=b[1]能不报错吗?
温馨提示:数组存储的是地址,他和整数常量存储的方式不一样,你改变b就等于改地址,原本最初的定义的是b[3],通过t--,你成功让b数组定义成了b[0],如果有b[1]难道不应该出现数组越界吗?
t的变化导致数组越界了。