多级数组内的字符串和整数
我正在尝试做比分配课程所需要的多一点。最终,我将随机获得以下数据。我无法弄清楚如何对数组的数字部分进行数学运算。现在,我使用字符串来存储数组,并且数值被存储为字符串。我试着做一个对象[] [] ....我不知道如何做对象的数学。多级数组内的字符串和整数
是否有存储多维(堆叠?)阵列作为字符串等为整数的一些值的方法吗?
我知道它不是只显示数组的偶数对象。我改变了代码,以便获得帮助。我在家里的版本中确实有这个功能。
我尝试使用上Initialising a multidimensional array in Java找到的信息,但它没有给出一个解决方案,我可以做的工作。
非常感谢!
import java.util.Random;
public class StackedArrayTest {
public static void main(String[] args) {
String[][] stats = new String[][] { { "Str", "6" }, { "Con", "3" },
{ "Int", "5" }, { "Wis", "8" }, { "Dex", "2" },
{ "pAtk", "0" }, { "mAtk", "0" }, { "AC", "0" },
{ "Mana", "0" }, { "HP", "0" } };
System.out.println("There are " + stats.length
+ " objects in the array.");
System.out.println("The first object in the array is: " + stats[0][0]
+ ".");
System.out.print("Even objects in array are: ");
for (int i = 0; i < stats.length; i = i + 1) {
if (i <= stats.length - 3) {
stats[i][1] = (stats[i][1]);
System.out.print(stats[i][1] + ", ");
} else
System.out.println(stats[i][1]);
}
}
}
要么使用Map<String, Integer>
或修改
for(int i=0; i < stats.length; i = i + 1) {
if (i <= stats.length - 3) {
stats[i][1] = (stats[i][1]);
System.out.print(stats[i][1] + ", ");
}
else System.out.println(stats[i][1]);
}
到
for(int i=0; i < stats.length; i = i + 1) {
if (i <= stats.length - 3) {
try {
System.out.print(Integer.parseInt(stats[i][1]) + ", ");
} catch(NumberFormatException ignore){/* ignore this */}
}
else {
try {
System.out.println(Integer.parseInt(stats[i][1]) + ", ");
} catch(NumberFormatException ignore){/* ignore this */}
}
}
这很好,非常感谢你的帮助。我试图做类似的事情,但我在错误的地方有Integer.parseInt,我没有使用catch。 – Bryan
我建议你使用 “HashMap的”,因为它可以定义类型键和值
HashMap<String, Integer> stats = new HashMap<String, Integer>();
stats.put("Str", 6);
stats.put("Con", 3);
// And so on...
System.out.println(""+(stats.get("Str")+1)); //4
到目前为止,我正在玩弄HashMap和漂亮的光滑。我被要求在这个任务中使用一个数组,并且我有很多的读法来弄清楚什么是HashMap可以做的事情,因为我从来没有听说过它,直到你的帖子。我已经改变了我的使用HashMap的效果。感谢您的回复/信息! – Bryan
你需要一个'Map'也许? –