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

时间:2014-11-15 04:54:19

标签: java arrays arraylist ascii

我正在努力制作一个能够完成标题所说的方法。我想我已经完成但由于某种原因每次我尝试调用此方法时都会出错。我总是让阵列出界。 有人可以指出我的错误吗? 我总是在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;
}

}

1 个答案:

答案 0 :(得分:1)

您正在将数组初始化为0,因为此时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()];

或者在您填充ascii[]列表

之后移动digits[]commandLineString的声明