【发布时间】:2016-02-08 02:19:18
【问题描述】:
import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
问题:用户将输入位数,程序会从中生成一个我自己编写的代码但似乎不起作用的数字。
运行程序时:
- 输入似乎工作正常。我试图测试输出的
-
没有第二个循环计算的数组,似乎工作 但随着计算似乎粉碎:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at tar0.main(tar0.java:17)
怎么了?
【问题讨论】:
-
Java 使用从 0 开始的索引。有效索引为 0..(d-1)
-
请在发布之前尝试正确格式化您的代码(实际上,只要始终正确格式化您的代码,这将增加可读性并更容易发现错误或理解代码的作用)。另外,尽量遵循命名约定(例如:类名应以大写字母开头,变量以小写字母开头)。
标签: java arrays indexoutofboundsexception digits