从String中添加数字

时间:2016-04-21 17:25:17

标签: java string char character add

我希望能够分离两个数字的字符串,然后将它们一起添加,但我不断获得每个字符的int值。如果我输入“55”作为字符串,我希望答案是10.我怎么能这样做?

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

3 个答案:

答案 0 :(得分:1)

你得到了字符的ascii值;您可以使用Character.digit(char, int)来获取数值。像,

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

输出(按要求)

10

答案 1 :(得分:0)

您可以使用string.toCharArray()方法,然后在for循环中添加它们

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

答案 2 :(得分:0)

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