0
package code;

public class Solution3 {

    public static int sumOfDigit(String s) {
        int total = 0;
        for(int i = 0; i < s.length(); i++) {
            total = total + Integer.parseInt(s.substring(i,i+1));
        }
        return total;
    }

    public static void main(String[] args) {
         System.out.println(sumOfDigit("11hhkh01"));
    }
}

コードを編集して、文字を無視し、入力からの数字を合計するにはどうすればよいですか? エラーはException in thread "main" java.lang.NumberFormatException: For input string: "h"

4

1 に答える 1

0

次のコード行は NumberFormatException をスローするためです。

Integer.parseInt("h");

Integer.parseInt文字「h」から数値を解析する方法がわかりません。

数字以外の文字を無視するには:

for(int i=0; i<s.length(); i++){
    try {
        total = total + Integer.parseInt(s.substring(i,i+1));
    catch(NumberFormatException nfe) {
        // do nothing with this character because it is not a number
    }
}
于 2015-02-16T02:55:17.757 に答える