Write a program to find sum middle 2 or 3 digits (if odd number of digits) of an entered number.
Example: for even number of digits
Input
4567
Output
5+6=11
2nd Example: for odd number of digits
Input
123
Output
2
3rd e.g.
Input
12345
2+3+4=9
import java.util.Scanner;
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter the number: ");
String number = keyBoard.nextLine();
if (number.length() >= 3) {
if (number.length() == 3) {
System.out.print(number.charAt(number.length() - 2));
} else {
int sum = 0;
for (int i = 1; i < number.length() - 2; i++) {
sum += Character.getNumericValue(number.charAt(i));
System.out.print(number.charAt(i) + " + ");
}
sum += Character.getNumericValue(number.charAt(number.length() - 2));
System.out.print(number.charAt(number.length() - 2) + " = " + sum);
}
} else {
System.out.println("Wrong number");
}
keyBoard.close();
}
}
Comments
Leave a comment