I've created a simple GUI that's purpose is to square or cube a given number that the user enters into the textfield. This all works fine but what I now want to do is to fine-tune it by testing the input. For example if the user enters a non-numerical value my program returns a message in the "Result" textfield telling them that the input was invalid.
However when i start the input with a number and follow it with, say, the letter K, it returns an error message. How do I fix this?
This is my code so far:
public static boolean squared()
{
String value = input.getText();
if( value == null || value.length() == 0 ){ // If value isn't equal to zero then do the following:
Result.setText("Invalid input entered!");
return false;
} else{
for(int i = 0; i < value.length(); i++)
if (!Character.isDigit(value.charAt(i) ) ){ // Use isDigit() of the character class to test if the character is a digit
Result.setText("Non-numerical key entered!");
return false;
}else{
int toSquare = Integer.parseInt(value); // Converts the string to an integer value
int squared = (toSquare * toSquare);
String converted = Integer.toString(squared); // Convert back to a string
Result.setText(converted);
}
return true;
}
}
Any ideas anyone?