2

I'm writing a program (code shown below) where the user can input a string with numbers. These are then converted from a string to an integer. But what I really want is a new array, where each individual number is a value. So if the user writes "15623" I want the array to be like {1, 5, 6, 2, 3} Does anyone know how to do it?

String getNumbers = textField.getText();                            
String[] ary = getNumbers.split(" ");
int intNumbers = Integer.parseInt(getNumbers);

int iArr[] = {intNumbers};
Arrays.sort(iArr);
for (int number : iArr) {
    textField.setText("" + number);
}
1
  • 2
    getNumbers.split("") without space Commented Apr 29, 2015 at 7:47

3 Answers 3

4

Use charAt to get specific characters and getNumericValue to convert a character to a digit :

String nums="1235325";
int[]  iArr = new int[nums.length ()];
for (int i = 0; i < nums.length (); i++) {
  iArr[i]=Character.getNumericValue (nums.charAt (i));
}
Arrays.sort (iArr);
System.out.println (Arrays.toString (iArr));

Output :

[1, 2, 2, 3, 3, 5, 5]
Sign up to request clarification or add additional context in comments.

1 Comment

I really love you. Thanks a lot! Tons of love!! :)
0

You can do

int iArr[] = new int[numString.length()];
for(int i=0;i<numString.length();i++)
     iArr[i]=Character.getNumericValue(numString.chatAt(i))

Comments

0

Hi if i understood the question you just need to split your input string on "" rather than " ".

String[] ary = getNumbers.split("");//This array will now look like {"1", "5", "6", "2", "3"}

Edit: Fixed output appearance

1 Comment

No. It looks like {"1", "5", "6", "2", "3"}. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.