2

学校向けに、10 進数から 2 進数、8 進数、16 進数、基数 20 (基数 36 の機能まで追加) の電卓を作成しています。それは機能し、いくつかの例外をキャッチしますが、10 進数 (数値システムではなく 4.5 など) の値が入力されたときに奇妙なことを行います。それをキャッチして、ユーザーをコードの先頭に戻し、「もう一度やり直して整数を入力してください」と言わせたいのですが、ifステートメントを使用してそれを行う必要があると考えています。 「xは整数」を条件にする方法。ちなみに私はJavaを使っています。

これは私が取り組んでいる私のコードの一部です:

public class mainconvert //creates my main class

{ //start mainconvert

    public static int manualparse(String m)//initializes an int method for a manual parse instead of using the library
    {//start manualparse

        int parsedvalue = 0;//creates an int that the parsed value will go into
        char[] split = m.toCharArray();//takes the input and splits it into an array of characters so we can take each individual character and convert it to an int
        int n = 0;//creates an int that will be used for the power that 10 is raised to while converting the input place

        for(int o=m.length()-1; o>=0; o--)//creates a for loop that takes each place in the array and loops through the conversion process until every place is converted
        {//start conversion for
            parsedvalue += Math.pow(10,n)*(split[o]-'0');//does the math, takes the char in each place, gets its ascii value, subtracts ascii 0 from that and multiplies it by 10^n, seen previously
            n++;//increases n (the exponent) by 1 after each loop to match the place that is being worked on
        }//end conversion for

        return parsedvalue;//returns the final parsed value
    }//end manualparse

    public static void main(String args[])//creates the main entry point
    {//start main

        JOptionPane pane = new JOptionPane();//makes JOptionPane "pane" so I don't have to type out "JOptionPane"

        boolean binput = false;

        do{//start do for do while loop for the reset on the exception catcher

            try{//start try for exception catcher

                String input = pane.showInputDialog("Enter value for conversion");//makes a Jpane with an input box for the value to be converted
                StringTokenizer toke = new StringTokenizer(input);//makes a string tokenizer for the input
                String k = toke.nextToken();//uses toke.nextToken to grab the token put into the input box so it can be used, it is made into a string
                int x = manualparse(k);//uses the manual parsing method created earlier to parse the token grabbed in string k into an int for use in our conversions

// then a bunch of calculator stuff and here's the end of the try/catch and do while loop

}//end try for exception catcher

catch(Exception ex)//catches exception

{//start catch

binput = true;//changes boolean to true to trigger do while loop

pane.showMessageDialog(null, "Please try again and input an integer");//displays error

}//end catch

}while(binput==true);//while for do while loop, triggers while the boolean binput is true
4

3 に答える 3

2

ユーザーは文字列形式で入力を入力します。その文字列が正しくフォーマットされているかどうかを確認してください。

boolean valid;
int input;
String inputString = ...;
try
{
    input = Integer.parseInt(inputString, 36);
    valid = true;
} catch (NumberFormatException e)
{
    valid = false;
    input = 0;
}

または、より直感的なソリューション:

boolean valid = inputString.matches("(+|-)?[0-9a-zA-Z]+");
于 2012-12-06T13:43:12.807 に答える
0

Integer.parseInt() は int 範囲内の数値の解析に制限されているため、より大きな数値を処理する場合は制限が厳しすぎる可能性があります。対応する Long.parseLong() がありますが、任意の大きな数の場合は、これを使用します。

try {
    new BigInteger(input, 36); // or whatever base
} catch (NumberFormatException e) {
    // bad input
}
于 2012-12-06T13:49:27.617 に答える
0

問題はあなたがすることです

parsedvalue += Math.pow(10,n)*(split[o]-'0');

それが数値であることを検証せずにsplit[o]。任意の文字である可能性があり.ます;)

テキストを検証する必要がある- '0'のは、何から差し引いても例外がスローされないためです。

ところで: オブジェクトを作成したり、 pow を使用して数値を解析したりするのは非常にコストがかかります。両方を避けるようにしてください。

これは、負の数、異なる基数、文字の検証を処理するが、オブジェクトを作成したり、Math.pow を使用したりしない例です。

public static long parseLong(String s, int base) {
    boolean negative = false;
    long num = 0;
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        int value = Character.getNumericValue(ch);
        if (value >= 0 && value < base)
            num = num * base + value;
        else
            throw new NumberFormatException("Unexpect character '" + ch + "' for base " + base);
    }
    return negative ? -num : num;
}
于 2012-12-06T14:00:21.477 に答える