String and Integer inside a multi-level array
I'm trying to do a little more than required for an assignment in class. Ultimately I'm going to have the following random for stats. I'm having trouble figuring out how to do math to the number part of my 开发者_运维问答array. Right now, I'm using a String to store the array and the number values are being stored as strings. I've tried doing an Object[][] .... and I can't figure out how to do math on the object.
Is there a way to store some values of a multidimensional (stacked?) array as strings and others as integers?
I know it's not showing only the even objects of the array. I changed the code around so it'd be easier to get help with. I do have this working in my version at home.
I tried using the information found on Initialising a multidimensional array in Java but it does not give a solution that I could make work.
Thank you very much!
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]);
}
}
}
Either use a Map<String, Integer>
or modify
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]);
}
to
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 */}
}
}
I suggest you to use "HashMap" since it can define types for both keys and values
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
精彩评论