I'm having issues with the code below, why am I not able to check if "if(Person[i][0] < 18)" I get error stating "Incomparable types".
I have found articles stating that I can use "if (Person[i][0].equals(18)), but how can I check if it is greater than?
Object[][] Person = new Object[2][2];
Person[0][0] = "John";
Person[0][1] = new Integer(18);
Person[1][0] = "Mike";
Person[1][1] = new Integer(42);
for(int i = 0; i < Person.length; i++)
{
System.out.print(Person[i][0]);
System.out.print("\t" + Person[i][1] + "\t");
if(Person[i][0] < 18)
{
System.out.print("18 or over");
}
System.out.println();
}
您必须输入大小写的对象以整数形式,例如:
if((int)Person[i][1] > 18)
It's extended version could be something like below. You might want to avoid string check. Go for Integer comparison only.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Object[][] Person = new Object[2][2];
Person[0][0] = "John";
Person[0][1] = new Integer(18);
Person[1][0] = "Mike";
Person[1][1] = new Integer(42);
for(int i = 0; i < Person.length; i++)
{
for(int j = 0; j < Person.length; j++)
{
System.out.print("\t" + Person[i][j] + "\t");
if(Person[i][j] instanceof Integer)
{
if((int)Person[i][j] > 18)
System.out.print("18 or over");
}
}
System.out.println();
}
}
}
I would recommend you to use Map which could be the best solution for this. Check the code below.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Map<String, Integer> person = new HashMap<>();
person.put("John", 18);
person.put("Tim", 32);
person.put("Georges", 39);
person.put("Mike", 45);
person.put("Vikor", 17);
//interate this map
Iterator<Map.Entry<String,Integer>> itr = person.entrySet().iterator();
while(itr.hasNext()){
Map.Entry<String,Integer> p = itr.next();
System.out.print(p.getKey() +" - "+p.getValue());
if(p.getValue() >= 32)
System.out.print("\t 32 or over");
System.out.println();
}
}
}
It might be helpful for someone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.