开发者

Math.sqrt function

    import javax.swing.JOptionPane;

public class PredefinedClass {
    public static void main(String[] args){
        do{
            String input = JOptionPane.showInputDialog("Enter a character:");
            if(input.length() > 1){
                JOptionPane.showMessageDialog(null,"Inva开发者_运维知识库lid Input. Input a character only.");
            }else if(Character.isLetter(input.charAt(0))){
                if(Character.isUpperCase(input.charAt(0))){
                    JOptionPane.showMessageDialog(null,"The character is an Uppercase letter.");
                }else if(Character.isLowerCase(input.charAt(0))){
                    JOptionPane.showMessageDialog(null,"The character is a Lowercase letter.");
                }
            }else if(Character.isDigit(input.charAt(0))){
                JOptionPane.showMessageDialog(null,"The character is a digit."+
                                                   "\nThe square root of "+input+" is "+Math.sqrt(input.charAt(0)));

            }
        }while(JOptionPane.showConfirmDialog(null,"Try again?[Y/N]","Try again?[Y/N]",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);
    }
}

Math.sqrt(input.charAt(0)) when i try 9 it's outputting 7.54 which should be 3. Why is it?


input.charAt() returns the character, not the numeric value of the digit. This means you're getting '9', as opposed to 9. The ASCII value of '9' is 57, so you end up taking the square root of that.

Try Math.sqrt(input.charAt(0) - '0') instead.

If you want to make your code a little bit more generic, consider using Integer.valueOf() or Double.valueOf() instead of looking at the individual characters.


You can also do -

Math.sqrt(Double.parseDouble(String.valueOf(input.charAt(0))));

Turn the char to string and parse double from the string.


Your problem is that you use the number nine ASCII code not nine as integer.

char c = input.charAt(0);

after that you perform the Math.Sqrt(c), now the char is cast to int.

the so the Math.Sqrt get 57 as parameter.

For proper work you should parse the character to Integer like Bala R answered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜