Cooln
Cooln

Reputation: 21

Java new array value per number

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);
}

Upvotes: 2

Views: 176

Answers (3)

Greg King
Greg King

Reputation: 140

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

Upvotes: 0

singhakash
singhakash

Reputation: 7919

You can do

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

Upvotes: 0

Eran
Eran

Reputation: 393966

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]

Upvotes: 4

Related Questions