0

我正在解决与ISBN 图书代码相关的问题。我需要制作程序,以便输入所需的 10 位代码中的 9 位。第 10 个是“?” . 程序需要输出适当的数字。我首先将输入字符串拆分为两个子字符串,无论是“?” 被检测到。

我的问题是如何从输入字符串中获取每个整数(所以我可以将这些整数与某些数字相乘以获得最终答案)

例如:输入字符串为:' 01234?6789 '

如何从该字符串中提取所有数字,以便可以对这些数字执行所有数学运算

4

2 回答 2

0

这样的事情对你有帮助吗?

private static int getCharAsInt(int x, String number) {
        if ((int) number.charAt(x) - 48 > 9){
            //do something if the char is "?"
            //maybe return -1 to know its not a number you can use
            return -1;
        }
        else //return the char as an int
            return (int) number.charAt(x) - 48;
    }

此方法将位置 x 处char的“数字”作为 an 返回,并在找到 时返回。并不是说当你找到.Stringint-1"?""?"

无论如何,当你这样称呼它时:

String string = "01234?6789";
for(int i = 0; i < string.length(); i++)
    System.out.print(getCharAsInt(i, string) + " ");

输出将是:

0 1 2 3 4 -1 6 7 8 9

当然,该方法返回一个int,因此您可以调用它并执行您想要获得最终答案的任何操作。

希望这可以帮助

于 2014-08-04T13:38:04.887 回答
0

这包含一些您应该学习的语句序列。见评论。

// checks whether the ten digits in the int[] make up a valid ISBN-10
private boolean isValid( int[] digits ){
    int sum = 0;
    for( int i = 0; i < digits.length; i++ ){
        sum += (10 - i)*digits[i];
    }
    return sum % 11 == 0;
}

// Expect a string with 9 or 19 digits and at most one '?'
public String examine( String isbn ){
    if( isbn.length() != 10 )
        throw new IllegalArgumentException( "string length " + isbn.length() );
    if( ! isbn.matches( "\\d*\\??\\d*" ) )
        throw new IllegalArgumentException( "string contains invalid characters" );
    // Now we have 9 or 10 digits and at most one question mark.
    // Convert char values to int values by subtracting the integer value of '0'
    int qmPos = -1;
    int[] digit = new int[10];
    for( int iDig = 0;  iDig < isbn.length(); iDig++ ){
        char c = isbn.charAt(iDig);
        if( c == '?' ){
             qmPos = iDig;
             digit[iDig] = 0;
        } else {
            digit[iDig] = c - (int)'0';
        }
    }
    // If qmPos is still -1, there's no '?'
    if( qmPos == -1 ){
        // Is it a valid ISBN-10?
        if( isValid( digit ) ){
            return Arrays.toString( digit );
        } else {
             throw new IllegalArgumentException( "not a valid ISBN" );
        }
    }

    // Which digit can replace '?'?
    for( int probe = 0; probe <= 9; probe++ ){
        digit[qmPos] = probe;
        if( isValid( digit ) ){
            // found it - return the completed ISBN-10
            return Arrays.toString( digit );
        }
    }
    // Failure
    throw new IllegalArgumentException( "no digit completes an ISBN" );
}
于 2014-08-04T17:01:01.253 回答