繁体   English   中英

使用自己的方法将字符串从args数组转换为单个变量int

[英]Convert a string from args array to a single variable int with own method

我正在尝试一种方法,可以按照标题所述进行操作。 我想我已经完成了,但是由于某种原因,每次我尝试调用此方法时,都会收到错误消息。 我总是越界越好。 有人可以指出我的错误吗? 我总是将数字发送到java ClassName之后的第二位。例如,如果我输入java ClassName 2568,则将args [1]发送到该方法。

public static int shiftHarder ( String commandLineInput )
{
    ArrayList <Character> commandLineString = new ArrayList <Character>();
    int counter;
    int number = 0;
    int ascii [] = new int [commandLineString.size()];
    int digits [] = new int [commandLineString.size()];

    for ( counter = 0; counter < commandLineInput.length(); counter++ )
    {
        commandLineString.add ( commandLineInput.charAt( counter ) ); 
    }

    for ( counter = 0; counter < commandLineString.size(); counter++ )
    {
        ascii [counter] = (int) commandLineString.get (counter);
    }

    if ( ascii [0] == 45 || ascii [0] == 43 )
    {
        for ( counter = 0; counter < ascii.length - 1; counter++ )
        {
            digits [counter] = ascii [counter + 1] -48;
        }

        if ( ascii [0] == 45)
        {
            for ( counter = 0; counter < digits.length; counter++ )
            {
                number = number*10;
                number = number + digits [counter];
            }
            number = - number; 
        }
        else
        {
            for ( counter = 0; counter < digits.length; counter++ )
            {
                number = number*10;
                number = number + digits [counter];
            }
        }           
    }

    else
    {
        for ( counter = 0; counter < ascii.length; counter++ )
        {
            digits [counter] = ascii [counter] -48;
        }

            for ( counter = 0; counter < digits.length; counter++ )
            {
                number = number*10;
                number = number + digits [counter];
            }
    }

    return number;
}

}

您正在初始化数组以使其大小为零,因为此时commandLineString为空:

int ascii [] = new int [commandLineString.size()];
int digits [] = new int [commandLineString.size()];

你可能是说

int ascii[] = new int[commandLineInput.length()];
int digits[] = new int[commandLineInput.length()];

否则,在填充commandLineString列表之后,将ascii[]digits[]的声明移到

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM