0

I want to be able to separate a String of two numbers and then add them together, but I keep getting the int value of each character. If I enter "55" as a string I want the answer to be 10. How can I do that?

package org.eclipse.wb.swt;

import java.util.*;

public class ISBN13 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

      Scanner input = new Scanner(System.in);

      System.out.println("enter a string");
      String numbers = input.nextLine();  //String would be 55

      int num1=numbers.charAt(0); //5

      int num2=numbers.charAt(1); //5

      System.out.println(num1+num2); //the answer should be 10
    }
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
GuillermoS
  • 25
  • 3

3 Answers3

1

You are getting the ascii value of the characters; you can use Character.digit(char, int) to get the numeric value. Something like,

String numbers = "55";
int num1 = Character.digit(numbers.charAt(0), 10);
int num2 = Character.digit(numbers.charAt(1), 10);
System.out.println(num1 + num2);

Output is (as requested)

10
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You can use string.toCharArray() method and then add them in a for loop

import java.util.Scanner;

public class MyClass {
    public static void main(String[] args) {
        Scanner scan = null;
        try {
            scan = new Scanner(System.in);
            String line = scan.nextLine();
            char[] charArray = line.toCharArray();
            int sum = 0;
            for (char character : charArray) {
                sum += Integer.parseInt(String.valueOf(character));
            }
            System.out.println(sum);
        } finally {
            scan.close();
        }
    }
}
saurabh kedia
  • 321
  • 2
  • 11
0
int x = Character.getNumericValue(element.charAt(0));
sjr59
  • 93
  • 1
  • 9