0

So I am trying to figure out how to skip an argument if it contains a certain type for instance:

args: Blue 3 Red 7 Green 5 Yellow 2

I am wanting to store the numbers in an array and the colors in a separate array. So if args[i] is a string then store it in the color array and if it is an int store it in the numbers array. Something like if(args[i] == String) then so on and so forth. Obviously that doesn't work though so I was looking for another solution.

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
        }
    }

Thanks for the help in advance.

Harry Manback
  • 41
  • 1
  • 6
  • You may be looking for `instanceof` -- but since `args` is a `String[]`, _all_ of its elements will be String (or null). `instanceof` is often (but not always) a clue that you haven't gotten your abstractions quite right; you may be able to define an interface with a do-a-thing method, and several implementations of that (do-a-thing with a String, do-a-thing with an int, etc). – yshavit Feb 28 '19 at 05:47
  • All args are Strings, try converting them – Scary Wombat Feb 28 '19 at 05:49
  • In order to determine whether a `String` contains digits only, use [static] method `parseInt(String)` of class `java.lang.Integer`. – Abra Feb 28 '19 at 05:49
  • i think this question would help you, https://stackoverflow.com/questions/237159/whats-the-best-way-to-check-if-a-string-represents-an-integer-in-java – Alpit Anand Feb 28 '19 at 05:52
  • wouldn't some rules on argument input help? e.g. mandate it to input as `Blue:3 Red:7 Green:5 Yellow:2` – dkb Feb 28 '19 at 06:24

5 Answers5

2

Try this

public class Main {
    public static void main(String[] args)
    {
        String[] colors = new String[args.length] ;
        int color_ix=0;
        int number_idx=0;
        Integer[] number = new Integer[args.length] ;
        for(int i = 0; i < args.length; i++)
        {
            if(args[i]==null) {continue;}
            try
            {
               number[number_idx]=Integer.parseInt(args[i]);
               number_idx++;
            }
            catch(NumberFormatException e)
            {
              colors[color_ix]=args[i];
              color_ix++;
            }
        }
        System.out.println("-----Number-----");
        for(int i=0;i<number_idx;i++)
        {
          System.out.println(number[i]);
        }
        System.out.println("-----Colors-----");
        for(int i=0;i<color_ix;i++)
        {
          System.out.println(colors[i]);
        }
    }
}

ouput $ java Main Blue Green 3 Red 2 Black 1

-----Number-----
3
2
1
-----Colors-----
Blue
Green
Red
Black
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
satyesht
  • 499
  • 7
  • 19
2

Try this:

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();
    }
}
Mark Melgo
  • 1,477
  • 1
  • 13
  • 30
2

You can simply

1. create ArrayList for numbers and strings

2. Add values to lists according to regex match which checks if the argument is number or string

3. convert ArrayList to arrays

public static void main(String[] args) {

    List<Integer> numberList = new ArrayList<>();
    List<String> strList = new ArrayList<>();

    for (int i = 0; i < args.length; i++) {
        if (Pattern.matches("-?\\d+", args[i])) {
            numberList.add(Integer.parseInt(args[i]));
        } else {
            strList.add(args[i]);
        }
    }
    String[] colors  = strList.toArray(new String[0]);
    int[] number = ArrayUtils.toPrimitive(numberList.toArray(new Integer[numberList.size()]));
}
Vebbie
  • 1,669
  • 2
  • 12
  • 18
  • For better performance, we should compile the `Pattern` outside of the for loop and re-use it for different strings. Internally, `Pattern.matches(..` does this -> `Pattern.compile(regex).matcher(input).matches()`. – Darshan Mehta Feb 28 '19 at 10:41
  • @DarshanMehta: Thanks for your suggestion. – Vebbie Feb 28 '19 at 11:24
1
public static void main(String[] args) {
    // args = Blue 3 Red 7 Green 5 Yellow 2
    String[] colors = Arrays.stream(args).filter(str -> str.matches("\\D+")).toArray(String[]::new);
    int[] number = Arrays.stream(args).filter(str -> str.matches("[-+]?\\d+")).mapToInt(Integer::parseInt).toArray();

    System.out.println(Arrays.toString(colors));    // [Blue, Red, Green, Yellow]
    System.out.println(Arrays.toString(number));    // [3, 7, 5, 2]
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
1

You can use Apache Commons Lang StringUtils.isNumeric to check if it is number.

//initialized with max length
String[] colors = new String[args.length];
int[] number = new int[args.length];
int colorIndex=-1;
int numberIndex=-1;
for(int i = 0; i < args.length; i++)
{
    //if number add to number array else to colors
    if(StringUtils.isNumeric(args[i])){
        number[++numberIndex]=Integer.valueOf(args[i]);
    }else{
        colors[++colorIndex]=args[i];
    }
}
Vikas
  • 6,868
  • 4
  • 27
  • 41