GuillermoS
GuillermoS

Reputation: 25

Adding numbers together from a String

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
    }
}

Upvotes: 0

Views: 162

Answers (3)

saurabh kedia
saurabh kedia

Reputation: 331

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();
        }
    }
}

Upvotes: 0

sjr59
sjr59

Reputation: 93

int x = Character.getNumericValue(element.charAt(0));

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

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

Upvotes: 1

Related Questions