我在学校有一个项目,我不知道我做错了什么。我必须询问用户他们想要输入多少个号码,并输入每个号码。然后我必须显示每个数字。当我做错时,有人能告诉我吗? 到目前为止我的代码:
public class Array_practice {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to enter?");
int a = input.nextInt();
int b = a;
int[] num = new int[b];
int s = 1;
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter number " + s + " : ");
num[i] = input.nextInt();
s++;
}
System.out.println("---------------------");
System.out.println("You entered: ");
for(int x = 0; x <= a; x++)
{
System.out.println(num[x]);
}
}
}
谢谢!
答案 0 :(得分:3)
for(int x = 0; x <= a; x++)
{
System.out.println(num[x]);
}
应该是
for(int x = 0; x < a; x++)
{
System.out.println(num[x]);
}
或者你将有ArrayOutOfBoundException,因为数组的第一个元素是0,最后一个是length-1