2

我正在为学校编写十进制到二进制到八进制到十六进制到以 20 为底的计算器(我添加了以 36 为底的功能)计算器。它可以工作并捕获一些异常,除了在输入小数(如 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() is restricted to parsing a number within the int range, so it may be too restrictive if you are handling larger numbers. There is the corresponding Long.parseLong(), but for arbitrarily large numbers, use this:

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'无论您从什么中减去它,doing 都不会引发异常,您也不希望它发生。

顺便说一句:创建对象或使用 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 回答