Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept two integers separated by a delimiter and print their sum

Tags:

java

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?

like image 922
Develper Avatar asked Oct 27 '25 05:10

Develper


2 Answers

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.

like image 141
Sebastian Heikamp Avatar answered Oct 28 '25 18:10

Sebastian Heikamp


You can try this:

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int A = sc.nextInt();
        sc.next().charAt(0);
        int B = sc.nextInt();
        System.out.println(A + B);
    }
}
like image 32
Lakshmi priya Avatar answered Oct 28 '25 17:10

Lakshmi priya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!