2014-03-19 180 views
0

我在我的申请一类其中int值存储:转换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数组值和转换字符串数组结果到单个字符串和作品!

我的问题是:我能够做一个完全相同的东西来int数组的数组?

  • 会改变int数组到字符串数组,字符串数组转换为一个字符串,然后将字符串转换为int是可怕的节目,但我的最好的解决办法?

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

我目前在Characters.class阵列的返回线获得StackOverflowError直到进程放弃。

+0

如果转换的int数组到一个整数。那个整数是多少? – Christian

+0

我不明白这个问题,但是你得到StackOverflowError,因为在你的方法中你调用递归的charPunch而没有退出条件 – Karura91

回答

2

我目前得到的StackOverflowError在Characters.class

这是因为你一遍又一遍地调用同一个方法,无需停止任何时候。基本上,这是你的代码看起来像什么(除了它的代码的其余部分):

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

所以它会调用自身具有相同的参数,并会做什么比填满堆内存,直到你得到你指出的错误。

可能的解决方案可能是在您的方法中添加一些逻辑来停止。或者,也许你想访问该数组的元素:现在目前执行charPunch方法可能会引发IndexOutOfBoundsException如果q值比的大小更大小于0或

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返回int

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

它不会编译。 int是原始类型,并且根本没有任何方法根本就没有。因此,您可以更改方法来返回Integer,而您可以访问toString方法,但通过这样做,上面的代码将将整数转换为字符串,以便将字符串转换为整数(再次),看起来好像无意义的。


我能够做同样的事情,以int类型的数组?

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

+0

这简直太尴尬了。谢谢。我曾尝试使用[q],但它一直在产生其他错误。现在它可以工作。 – TomFirth

+0

@ TomFirth84不客气。 –

0

有几个问题可以帮助你理解你的问题。

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

你想将整个int数组转换为一个字符串或只是通过函数传递的值?转让后的价值是什么?

无论哪种方式,你可能想看看数组列表和增强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 
}  
+0

@ Patty P:1)方法内部的整数值始终保持不变。 2)我真的不想将任何整数值转换为字符串,我希望有另一种解决方案。 3)我使用初始值来设置一个变量,从它们中减去,直到我得到一个结果,然后重新使用这些值来重置变量并重新开始。为了减少混乱,我把它们放在另一个类中。我喜欢你的答案。 – TomFirth

+0

谢谢我想你会想要一些包含你的值的静态最终副本的类常量类来重置你的值,一旦你完成它们。 –