How do I make my code check that the user has input a alphabetical character? [Java]
Update: the code works now. Thanks for help guys.
This is part of the code I'm having trouble with
if ((amount < 0) || (Character.isLetter(amount)))
Anyone know what I'm doing wrong? Here's a piece of my code:
try
{
if ( theStock.exists( pn ) ) // Button CHECK
{
thePicture.clear();
if ( actionIs.equals( Name.ADD ) ) {
try
{
amount = Integer.parseInt(theInputPQ.getText()); // Checks that
if ((amount < 0) || (Character.isLetter(amount))) { // number has been
theOutput.setText("Please enter sufficient No."); // input
}
else {
theStock.addSto开发者_开发技巧ck(pn, amount);
Product pr = theStock.getDetails( pn ); // Add to
theAction.setText( // stock of
pr.getDescription() + " : " + // item
theMoney.format(pr.getPrice()) +
" (" + pr.getQuantity() + ")" );
}
}
catch (NumberFormatException e) {
theOutput.setText("Please enter sufficient No.");
Product pr = theStock.getDetails( pn );
theAction.setText(
pr.getDescription() + " : " +
theMoney.format(pr.getPrice()) +
" (" + pr.getQuantity() + ")" );
if ( actionIs.equals( Name.ADD ) ) {
}
}
} else { // F
theAction.setText( // Inform Unknown
"Unknown product number " + pn ); // product number
}
}
You're checking if an int
is a letter or not:
Character.isLetter(amount)
If that int is for instance 65
that method would return true, because what in ascii code the number 65
represents the letter a
This is probably the source of your problems.
You may safely remove that validation, because, if after the call to Integer.parseInt
you may be sure that amount
is a number ( otherwise it will go to the catch( NumberFormatException )
section below as you may already have noticed.
Is amount
a int
variable? if it is, how it can be a letter (Character
)? if not int
, then how it can be compared using < 0
? It can be or character or integer, not both above.
Well I think that you are already checking if amount is an int by the:
Integer.parseInt(theInputPQ.getText());
and the try-catch block. don't need to do the
Character.isLetter(amount)
The amount < 0
check isn't doing anything useful, unless you are checking for integer values less than 0. Integer.parseInt()
returns the integer that it read, as a string. It throws a NumberFormatException
if its argument does not contain a parseable integer.
I would call a different method if your goal is just to figure out if the button's text has letters in it. Also, I'm not sure why you're calling isLetter()
on the text of a String. Here's an example I saw that goes character-by-character:
String str = theInputPQ.getText(); // I assume this is a String
for(int i=0; i < str.length(); i++)
{
if(Character.isDigit(str.charAt(i)))
System.out.println("It's a digit");
if(Character.isLetter(str.charAt(i)))
System.out.println("It's a letter");
}
In the interest of good coding practices, if you add this code then it should be a separate private method.
Sources: Java API for Integer, Dream in Code
精彩评论