将int数组转换为int

时间:2014-03-19 16:02:43

标签: java arrays int

我的应用程序中有一个类,其中存储了int值:

Characters.class:

public int charPunch(int q) {

    int[] charPunch = {
        15, 
        10, 
        20, 
        25, 
        20, 
        20, 
        15, 
        20, 
        20, 
        25
    };
    return charPunch(q);
}

q值由用户角色选择决定。我正在尝试理解代码,因此只是发布了当前的代码。

在同一个类文件中,我有一个字符串数组,然后我可以使用.toString()转换(在另一个.class文件中);

Game.class:

oneName = Ch.charName(q).toString();

这为playerOne的oneName提供了数组值,并将String数组结果转换为单个String并且有效!

我的问题是:我能否对一组int值做同样的事情?

  • 将int数组更改为String数组,将String数组转换为单个String,然后将String转换为int是可怕的编程,但我的最佳解决方案是什么?

    String onePunch = charPunch(q).toString();
    int charPunchInt = Integer.parseInt(charPunch);
    

我目前在Characters.class数组的返回行上得到StackOverflowError,直到进程放弃。

2 个答案:

答案 0 :(得分:2)

  

我目前在Characters.class上获得StackOverflowError

这是因为您无需随时停止即可一遍又一遍地调用相同的方法。基本上,这是你的代码看起来的样子(除了代码的其余部分):

public int charPunch(int q) {
    return charPunch(q);
}

因此它将使用相同的参数调用自身,并且除了填充堆栈内存之外什么也不做,直到您收到指示的错误。

可能的解决方案可能是在您的方法中添加一些逻辑来停止。或者,您可能想要访问数组的元素:

public int charPunch(int q) {
    int[] charPunch = {
        15, 
        10, 
        20, 
        25, 
        20, 
        20, 
        15, 
        20, 
        20, 
        25
    };
    return charPunch[q]; //<- using brackets [] instead of parenthesis ()
}

请注意,如果charPunch的值小于0或大于所用数组的大小,IndexOutOfBoundsException方法的当前实现可能会抛出q


如果您尝试执行此代码:

String onePunch = charPunch(q).toString();
int charPunchInt = Integer.parseInt(charPunch);

由于您从int返回charPunch,因此无法编译。 int是原始类型,并且没有任何方法。因此,您可以更改方法以返回Integer而您将有权访问toString方法,但通过这样做,上面的代码将整数转换为字符串以将字符串转换为一个整数(再次),这似乎毫无意义。


  

我是否可以对int值数组执行完全相同的操作?

定义你真正想做的事情,然后你会得到预期的帮助。

答案 1 :(得分:0)

有几个问题可以解决你的问题。

函数charPunch(int q)中的整数值是否总是相同?

您是否尝试将整个int数组转换为String或仅通过函数传递的值?你在完成任务后对这个值做了什么?

无论哪种方式,您可能希望查看数组列表和增强的for循环语法(对于每个循环)。

实施例

// if values are immutable (meaning they cannot be changed at run time)
static final int charPunches [] = {15,10,20,25};

// function to return string value
protected String getCharPunchTextValue(int q){
    String x = null;
    for(int i: charPunches){ // iterate through the array
        if(q == i){// test equality
            x = Integer.toString(i);// assign string value of integer
        }
    }
    return x; // Return value, what ever needs this value may check for null to test if value exists
}