1. Member
Join Date
Feb 2012
Posts
11
Rep Power
0

## Sort Problem

Hey guys,
I'm trying to solve a problem in which the user keeps inserting numbers and everytime the user inserts a number the problem should sort the array.

This is the code I've done :
Java Code:
```public class ex5
{
public static void main(String Args[]){
Scanner input = new Scanner(System.in);
System.out.println("Quantos inteiros quer ler?");
int n_inteiros = input.nextInt();
int[] a = new int[n_inteiros];
for(int i=0;i<n_inteiros;i++){
a[i]=0;
}
int i=0;
while(i<n_inteiros){
int novo= input.nextInt();
a[i]=novo;
Arrays.sort(a);
i++;
}
for(int j=0;j<n_inteiros;j++){
System.out.println(a[j]);
}
}
}```
Now the output :
Java Code:
```Quantos inteiros quer ler?
3
1
2
3
0
1
3```
Thanks.

2. ## Re: Sort Problem

Try adding a print out of the array after every sort to see what is in it. Use the Arrays toString() method to format the array:
S.o.println(Arrays.toString(a));

3. Member
Join Date
Feb 2012
Posts
11
Rep Power
0

## Re: Sort Problem

Thanks Norm.
What's the S.o. for ?
I'm still a beginner :/

4. ## Re: Sort Problem

Sorry. S.o. should be System.out.

5. Member
Join Date
Feb 2012
Posts
11
Rep Power
0

## Re: Sort Problem

Wow, that's amazing.
Thanks a lot Norm.

Java Code:
```1
[0, 0, 1]
2
[0, 1, 2]
3
[0, 1, 3]```
That's what it does.
Basically it works until the 3, when we hit the three it replaces the last int for the 3 :o
I have no idea why though :/

6. ## Re: Sort Problem

Take a piece of paper and draw the array and set the value of i. change the array's contents at i and sort the array and increment i.
Do it again. Do you ever put an item into the array where there is currently another number? If so you replace that number.

Work through your code playing comuter with paper and pencil and you will see what it is doing.

when we hit the three it replaces the last int for the 3
What is the value of i?

7. Member
Join Date
Mar 2012
Posts
6
Rep Power
0

## Re: Sort Problem

I think you should sort the integer array after the integer from user is been inserted into the integer array.
This should be sort correctly everytime you print it at the end.