首页 > 解决方案 > 将二维数组中的字符串元素与 int 进行比较

问题描述

我在导航二维数组时遇到问题。假设我正在使用这个字符串数组:

String[][] guestList = {{"Adam Ason", "35"},
                {"Berta Bson", "70"},
                {"Ceasar Cson", "12"}};

我想将每位客人的年龄与 18 岁进行比较,以确定他们是否是成年人,然后打印出来,我该怎么做?到目前为止,我已经尝试过:

int tempAge;
int adultGuests = 0;
int childGuests = 0;

for (int i = 0; i < guestList.length; i++)
{
     for (int j = 0; j < guestList.length; j++)
     {
         tempAge = Integer.parseInt(String.valueOf(guestList[j]));
         if (tempAge <= 18)
         {
             childGuests += 1;
         }
         else
         {
             adultGuests += 1;
         }
     }
}

System.out.println("Adult guests: " + adultGuests);
System.out.println("Children guests: " + childGuests);
  

Intellij 告诉我将 ((guestList[j])) 包装在 String 中。valueOf但无论我是否这样做,我都会得到以下结果:

Exception in thread "main" java.lang.NumberFormatException: For input string: "[Ljava.lang.String;@5d22bbb7"
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.base/java.lang.Integer.parseInt(Integer.java:652)
        at java.base/java.lang.Integer.parseInt(Integer.java:770)
        at test2.main(test2.java:20)

标签: javaarrays

解决方案


你不需要内循环。您具有固定的结构,其中年龄始终位于1内部数组的索引处。

因此,您需要遍历外部数组并在 index 处对每个内部数组的元素求和1

public static void main(String[] args) {
    String[][] guestList = {{"Adam Ason", "35"},
            {"Berta Bson", "70"},
            {"Ceasar Cson", "12"}};
    int adultGuests = 0;
    int childGuests = 0;

    for (int i = 0; i < guestList.length; i++)
    {
        if (Integer.valueOf(guestList[i][1]) <= 18){
            childGuests += 1;
        }
        else {
            adultGuests += 1;
        }

    }

推荐阅读