java - 将二维数组中的字符串元素与 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)
解决方案
你不需要内循环。您具有固定的结构,其中年龄始终位于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;
}
}
推荐阅读
- javascript - 如何获取函数javascript的返回值
- python - 我可以同步 conda 配置吗?环境?
- javascript - 如何在 Python3 中创建带有倒数计时器的网页?
- javascript - 与 setState 回调相比,使用 componentDidUpdate 有什么优势?
- ruby-on-rails - simple_token_authentication - 未定义的方法`authenticate_user
- javascript - 我如何在 for Each 循环中使用间隔或超时
- python - 用于验证科学记数法的 RegEx
- docker - 从 docker-compose 连接到不同堆栈上的服务
- c# - ViewModel 中 MVC asp.net 中的自定义验证
- c# - 可能将数据库连接到服务器