Reputation: 2313
I don't know how to insert a line of code that counts the numbers entered in a box that pops up. Basically I can't enter more than 5 numbers. So I think some sort of if statement needs to be inputed, which I don't know how to do.
Here is my code:
String number;
number = JOptionPane.showInputDialog("Enter Number");
JOptionPane.showMessageDialog(null,"The new result is" + number,"Results",
JOptionPane.PLAIN_MESSAGE);
System.exit(0);
Thanks
Upvotes: 0
Views: 851
Reputation: 108957
EDIT: a little shabby but how about something like this?
while(true)
{
String number = JOptionPane.showInputDialog("Enter Number");
if(number.length() >5 )
{
JOptionPane.showMessageDialog(null ,"Too Long! try again",JOptionPane.PLAIN_MESSAGE);
}
else break;
}
Upvotes: 1
Reputation: 2051
There are some complications to this, you don't check for non-numeric characters, for instance.
String number = JOptionPane.showInputDialog("Enter number");
number = number.trim(); // remove any spaces before and after
if (number.length() > 5 || hasNonNumeric(String)) {
// show message
JOptionPane.showMessageDialog(null,"Too long or non numeric characters in the string",
JOptionPane.PLAIN_MESSAGE);
}
boolean hasNonNumeric(String pSrc) {
for (char c : pSrc.toCharArray()) {
if (!Character.isDigit(c)) {
return true;
}
}
return false;
}
This is a bit safer.
Upvotes: 0