Question:
In Java, how do we use a loop to display and calculate the sum of the evenly positioned digits?
Eg. If input is 29664 then output is 15 (9+6)
Eg. If input is 29664 then output is 15 (9+6)
Code:
import java.util.*; public class SumOfEvensPositions { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); String str = sc.nextLine(); try { Integer.parseInt(str); int total=0; for(int i=1;i<str.length();i=i+2){ System.out.println("Pos " + (i+1) + " : " + str.charAt(i)); total = total + Character.getNumericValue(str.charAt(i)); } System.out.println("Total: " + total); } catch(NumberFormatException e) { System.out.println("Invalid number"); } } }
Output:
$ java SumOfEvensPositions Enter a number: 29664 Pos 2 : 9 Pos 4 : 6 Total: 15