gpt4 book ai didi

java - 如果参数是某种类型,如何跳过它

转载 作者:行者123 更新时间:2023-11-29 10:08:41 25 4
gpt4 key购买 nike

所以我想弄清楚如何跳过包含特定类型的参数,例如:

参数:蓝色 3 红色 7 绿色 5 黄色 2

我想将数字存储在一个数组中,将颜色存储在一个单独的数组中。因此,如果 args[i] 是一个字符串,则将其存储在颜色数组中,如果它是一个整数,则将其存储在数字数组中。像 if(args[i] == String) then 等等。显然这行不通,所以我正在寻找另一种解决方案。

public class Main {
public static void main(String[] args)
{
String[] colors = new String[] {};
int[] number = new int[] {};
for(int i = 0; i < args.length; i++)
{
// stuck
}
}

提前感谢您的帮助。

最佳答案

试试这个:

public class Main {

public static void main(String[] args) {
List<String> colors = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();

for (int i = 0; i < args.length; i++) {
try {
numbers.add(Integer.parseInt(args[i]));
} catch (NumberFormatException e) {
colors.add(args[i]);
}
}

String[] colorsArray = colors.toArray(new String[0]);
int[] number = numbers.stream().mapToInt(num -> num).toArray();
}
}

关于java - 如果参数是某种类型,如何跳过它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54919126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com