如何克服Integer.parseInt(args [0])的ArrayIndexOutOfBoundException? [英] How can I overcome ArrayIndexOutOfBoundException for Integer.parseInt(args[0])?

查看:151
本文介绍了如何克服Integer.parseInt(args [0])的ArrayIndexOutOfBoundException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在其中一个视频教程中看到了下面的代码.它可以很好地执行,但是当我试图在系统中执行时,它可以很好地编译,但是却出现运行时错误提示,

I've seen below code in one of the video tutorial.There its executes fine but while I'm trying to execute in my system, it is compiling fine but I'm getting runtime error saying,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

class Test13 
{
    public static void main(String[] args) 
    {   
        int i = Integer.parseInt(args[0]);
        System.out.println(i);
    }
}

有人可以指导我这段代码有什么问题以及如何纠正吗?

Can someone please guide me what's wrong with this code and how to rectify?

提前谢谢!

推荐答案

ArrayIndexOutOfBoundsException .

例如:假设int a [] = {2,4,5,10,3}是一个数组.

For example: suppose int a[]={2,4,5,10,3} is an array.

数组的大小为5,索引从0开始.

the size of array is 5 and index starts from 0.

这意味着您的数组范围从索引0到索引4,其中索引0的元素是第一个元素(即2),索引4的元素是最后一个元素(即3)

Which means your array ranges from index 0 to index 4 where element at index 0 is the first element i.e. 2 and element at index 4 is the last element i.e. 3

如果您尝试访问索引范围不在0到4之间的任何元素,则会显示 ArrayIndexOutOfBoundsException ,因为数组中不存在此类索引.

if you try to access any elements at an index which is not in the range 0 to 4 it will show you ArrayIndexOutOfBoundsException because no such index exists in the array.

现在您的情况是 args 是命令行参数,这意味着您必须在运行代码时传递参数.

Now in your case args is command line argument which means you have to pass parameters when you run your code.

如果您是从终端运行代码,则在 java yourclassname 之后,您必须传递参数.

If you are running your code from terminal then after java yourclassname you have to pass parameters.

例如:java yourclassname 10 20 30

For example: java yourclassname 10 20 30

此处10 20 30是您的命令行参数,这些参数存储在 args 数组中,并且 args [0] = 10 args [1] = 20 args [2] = 30

here 10 20 30 are your command line arguments which get stored in your args array and args[0]=10 args[1]=20 args[2]=30

如果在运行代码期间未传递任何参数,则您的 args 为空,因此您将获得 ArrayIndexOutOfBoundsException

If you haven't passed any arguments during running your code your args is empty and therefore you will get ArrayIndexOutOfBoundsException

希望它可以帮助您理解命令行参数的概念.

hope it helps you to understand the concept of command line arguments.

这篇关于如何克服Integer.parseInt(args [0])的ArrayIndexOutOfBoundException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆