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,"Invalid 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 to9. The ASCII value of'9'is57, 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()orDouble.valueOf()instead of looking at the individual characters.