1

So I'm currently stuck on a bit of code, because I want to be able to have 2 command line arguments as 2 positive even numbers.

However if the user were to either input a number odd, less than 0 or more or less than 2 arguments, the code must output that the user has input an invalid number of arguments and terminate the program.

This is my code so far and I'm not sure where I'm going wrong:

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        int numOne = Integer.parseInt(args[0]);
        int numTwo = Integer.parseInt(args[1]);

        if ((numOne == null && numTwo == null)) {
            System.out.println("Not enough arguments. System terminating");
        } else if (numOne == null || numTwo == null) {
            System.out.println("terminating program");
        }
    }
}

Sorry if the code is messy, I'm new to this site and I'm not sure how to get the code settings. Thanks :)

1
  • You have to put the null check before parsing then Integers. You can't pass a null to parseInt(). Commented Mar 27, 2016 at 11:36

4 Answers 4

3

An int (which is a primitive type) can't be null, so your if (numOne == null || numTwo == null) condition can't even pass compilation. To check the number of command line arguments, check args.length before accessing args[i]. For example you should access args[1] only if args.length>1, otherwise you'll get an ArrayIndexOutOfBoundsException.

Note that you should also handle the case where the input arguments are not of the required type (i.e. they cannot be parsed to int).

if (args.length < 2) {
    System.out.println("Not enough arguments. System terminating");
} else {
    try {
        int numOne = Integer.parseInt(args[0]);
        int numTwo = Integer.parseInt(args[1]);
        ...
    }
    catch (NumberFormatException numEx) {
        System.out.println("Int arguments expected");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1
int numOne = Integer.parseInt(args[0]);

If the user does not give arguments at all, this will throw an ArrayIndexOutOfBoundsException. It will also throw an exception if the user doesn't input a number, but that doesn't seem to be part of your task, so let's just ignore that.

Before you do that you should check the args arrays length.

if (args.length != 2) doSomethingToTellTheUserHisArgumentNumberIsWrong();

After that you can parse the ints. No need to check them for null. Pointless anyway.

You also need to check for negative numbers (<0), which you don't so far. And if you need to find out if a number is odd you can do that with (number % 2 == 1) which will be true if the number is odd.

Comments

0

First you have to check the length of the array for 2 arguments. Then parse both argument one at a time and check for validation condition.

You can also write a simple utility function to check the even/odd integer, that will make your code more cleaner.

public static void main(String[] args) {

    try{
        if(args!=null&&args.length==2){
            int first = parseEvenNumber(args[0]);
            int second = parseEvenNumber(args[1]);
            System.out.println(String.format("First number: %d , Second number : %d", first, second));
        } else {
            System.err.println("Not enough arguments supplied. Please provide two arguments.");
        }
    }catch (NumberFormatException exception){
        System.err.println("Please enter a valid number.");
    }catch (Exception exception){
        System.err.println(exception.getMessage());
    }
}


private static int parseEvenNumber(String arg){
    int evenNumber = Integer.parseInt(arg);
    if(evenNumber>0&&evenNumber%2==0){
        return evenNumber;
    } else {
        throw new IllegalArgumentException("Number must be a positive even integer.");
    }
}

Comments

0

If you are running in a console, you need to use java commands like the below:
javac to compile e.g. javac test.java
java to execute e.g. java test

to pass arguments to the program:
java to execute e.g. java test 1 2 4

1 being args[0]
2 being args[1]
4 being args[2]

I saw that you import the java.util.Scanner library but I think you don't need that in your program.

You first need to check if the user inputs the right number of command line arguments and then check if the inputs are either odd or less than zero (0) as far as I understand on your requirement.

please see code suggestion below, you might want to change anything on your own preference:

public class test {

     public static void main(String[] args){
        
        if(args.length > 2)
        {
            System.out.println("Too much arguments. The system will terminate.");
        }
        else if(args.length < 2)
        {
            System.out.println("Not enough arguments. The system will terminate.");
        }
        else
        {
             int numOne = Integer.parseInt(args[0]);
             int numTwo = Integer.parseInt(args[1]);
             
             if ((numOne <= 0) || (numTwo <= 0) || (numOne % 2 == 1) || (numTwo  % 2 == 1)) {
                System.out.println("Invalid inputs. The system will Terminate.");
             }
             else
             {
                 //The inputs are valid
                System.out.println("Yahoo! The inputs are valid.");
             }
        }
        System.exit(0);
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.