数组 - 比较int

时间:2018-03-16 03:03:18

标签: java arrays

我在下面的代码中遇到问题,为什么我无法检查" if(Person [i] [0]< 18)"我收到错误陈述"无与伦比的类型"。

我发现文章说我可以使用" if(Person [i] [0] .equals(18)),但是如何检查它是否大于?

    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();
    }  

2 个答案:

答案 0 :(得分:2)

您必须将对象的大小写为整数,例如:

  if((int)Person[i][1] > 18)

答案 1 :(得分:0)

它的扩展版本可能如下所示。您可能希望避免字符串检查。只进行整数比较。

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();
        }
    }
}

我建议您使用地图,这可能是最佳解决方案。请检查以下代码。

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();
        }

    }
}

对某人可能有帮助。

相关问题