Skip to content
Advertisement

Accept two integers separated by a delimiter and print their sum

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int A = sc.nextInt().split(":");
        int B = sc.nextInt();
        System.out.println(A + B);
    }
}

If I’m given an input like 1:2 then the output should be 3. Likewise 54:6 then 60.

But I’m getting an error. What should I do to achieve that output?

Advertisement

Answer

You cannot call split on an integer, it is meant for splitting a String. Try this:

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] numbers = sc.next().split(":");
        int A = Integer.parseInt(numbers[0]);
        int B = Integer.parseInt(numbers[1]);
        System.out.println(A + B);
    }
}

Of course some validation would be nice (check if the String contains a colon, if the parts are numeric, etc.), but this should point you in the right direction.

Advertisement