User input and output
I have started some code, and I would like to be able to enter a number of no more than five numbers and the return result would place 5 spaces in between each number. So for instance I could type in 12345, then the box output would show 1 2 3 4 5. So firs开发者_开发知识库t off I need to be able to only enter 5 numbers, second there needs to be 5 spaces between each of them.
String number;
int number1;
number = JOptionPane.showInputDialog("Enter Number");
number1 = Integer.parseInt(number);
JOptionPane.showMessageDialog(null,"Th… new result is" + number1,"Results",
JOptionPane.PLAIN_MESSAGE);
System.exit(0);
Thanks
I didn't exactly get what U meant but i think it'll do what U wanted !
public static void main(String [] args)
{
String number;
number = JOptionPane.showInputDialog("Enter Number");
int b = number.length() ;
char [] a = new char [number.length() ] ;
for ( int i = 0 ; i < number.length() ;i++)
a[i] = number.charAt(i) ;
for (int i = 0 ; i < a.length ; i++)
{
number += ( a[i] );
number += ' ' ;
}
number = number.substring(b) ;
JOptionPane.showMessageDialog(null,"Th… new result is" + ' ' + number,"Results",
JOptionPane.PLAIN_MESSAGE) ;
System.exit(0);
}
First of all there is no need to convert the input to an int, since you are not using it for any numerical computations. The first part of your question is easily solved with an if statement.
if (number.length() > 5) ...
For the second part, I guess there are a lot of good ways to do it, and probably some libraries as well, but I came up with:
public static String addSpace(String s){
StringBuilder result = new StringBuilder();
for (char c : s.toCharArray())
result.append(c).append(' ');
return result.toString();
}
And so you call the addSpace method with number as argument.
Using the JOptionPane.showInputDialog(...) there is no way to validate the input on the fly (i.e checking that it only contains digits and is only 5 chars long), you'll have to do it after the user has sent it and if it's not valid throw up a new dialog. It works but it's not the prettiest way to do it. Maybe you should consider writing a custom dialog that validates the input using a DocumentListener added to the input text field in the dialog. You can read about it here (ctrl-f for CustomDialog).
If you think that is too complicated for the task at hand, this could be a nice approach to do the show-validate-showagainifinvalid stuff:
private String showInputDialog()
{
String inputValue = JOptionPane.showInputDialog("Please input 5 numbers from 0-9");
if(inputValue == null || inputValue.isEmpty() || !inputValue.matches("[0-9]{5}"))
{
inputValue = showInputDialog();
}
return inputValue;
}
then use the addSpace
method in one of the other answers.
精彩评论