so I would like to really shorten this code down possibly to a few lines. I'm extremely new to java so apologies if this question has been asked before.
I would like to store all the fields I have declared in my Main class in an array, but each are a different data type so I'm not sure how I would go about this. And then I would like to print corresponding field labelled with its specific datatype. It would ideally look something like : "My [datatype] is: [value stored]" for each declared field that I have declared. I imagine it condenses all the repeated print statements to one line based on the size of the array by using a for loop and looping through the size of the array, but am new to Java and am not particularly familiar with for loops and ranges. My code:
class Main {
static int a = 5;
static float b = 130.1f;
static double c = 55.5;
static boolean d = true;
static char e = 'h';
static String f = "Bg";
public static void main(String[]args){
System.out.println("My Number is " a);
System.out.println("My Float is " b);
System.out.println("My Double is " c);
System.out.println("My Boolean is " d);
System.out.println("My Char is " e);
System.out.println("My String is " f);
}
}
CodePudding user response:
To store objects of different types in an array, list or what ever you have to use their common base class. Primitive data types do not have a common base class but their class counterparts. Instead of declaring a string array just declase an Object[]
. "But 5 or 'h' is not a class?!" That's true but the data is automatically boxed in the correspondig wrapper class. And what is important, too - even if the array stores only objects of class Object
the concrete class is still available and can be retrieved at runtime to print the wanted information.
BTW - the code could look like this:
Object[] args = { 5, 130.1f, 55.5, true, 'h', "Bg" };
for (Object obj : args) {
System.out.println(String.format("My [%s] is: [%s]", obj.getClass().getSimpleName(), obj));
}
CodePudding user response:
Try this:
class Main {
static int a = 5;
static float b = 130.1f;
static double c = 55.5;
static boolean d = true;
static char e = 'h';
static String f = "Bg";
private static List arr = new ArrayList(Arrays.asList(a, b, c, d, e, f));
public static void main(String[] args) {
for (Object o : arr)
System.out.println("My " o.getClass().getName() " is " o);
}
}