1
public static void main(String[] args) {
    
    Scanner sc = new Scanner (System.in);
    System.out.println("Ingresa el número: ");
    Integer numero = sc.nextInt();
    char[] nums = numero.toString().toCharArray();
}
8
  • Where are you stuck? Jun 29, 2020 at 6:13
  • I don't know how I should calculate the sum of the digits Jun 29, 2020 at 6:14
  • What have you tried? numero has to be greater than 999 and less than 10000 doesnt it. Do that part, then maybe 7654 / 1000 == 7? Or convert char to int? Jun 29, 2020 at 6:17
  • I tried to convert the number into an array to try to calculate the sum of the first and last number, but I don't know how to do it Jun 29, 2020 at 6:21
  • do you mean, like i entered 2008, then it should do 2+8 = 10?
    – Siddhant
    Jun 29, 2020 at 6:25

4 Answers 4

1

I think this is what you are looking for. This algo will first check for the number of digits in the number, if they are 4 then allow to process further else it will say integer of 4 digits is allowed.

Scanner sc = new Scanner (System.in);
        System.out.println("Ingresa el número: ");
        Integer numero = sc.nextInt();
        if(Math.floor(Math.log10(numero)) + 1 != 4 ) {
            System.out.println("Integer should be of four digits");
        } else {
            int last = numero%10;
            int first = numero/1000;
            System.out.println(last+first);
        }
1
  • I hope it helped you . Would you mind giving an upvote and accept the answer for better visibility. Jun 29, 2020 at 6:40
1

I think this is what you want :

int answer = n%10 + n/1000;

It adds the first and last digit of the number n.

0

You can do something like this

Scanner sc = new Scanner (System.in);
System.out.println("Ingresa el número: ");
String numero = sc.nextLine();

Integer result = Integer.parseInt(numero.charAt(0)+"") +
    Integer.parseInt(number.charAt(numero.length()-1)+"");
0
0

You mean like this?

public class Adder {

    public static void main(String[] args) {
        int num=2008;
        
        //Find last number
        int sum = num%10;
        //Find first number
        while (num >= 10){
            num /= 10;
        }
        sum +=num;

        System.out.println(sum);
    }

}
1
  • @Scratte I edited it to be more clear. 1) num%10 always find the last number (I think of it like if you look at the times table of 10 you will find 2000, 1200, 130 but not the last digit- because the last digit is more than 10 and therefore not a multiple of it-, so that will be the remainder). 2) Then divide the number by 10 until the number is 10 or more, this finds the first number(Dividing the number by 10 until the there is only one digit)
    – Shennifer
    Jun 30, 2020 at 2:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.