I am supposed to create a file that will generate 100 random numbers and then sort them. I am stuck on the sorting. I think it would be a really simple solution but i cant seem to figure it out. I have tried the arrays utility and creating a method to sort but I keep getting a lot of zeros and i know that isn't right. I know something around line 32 isnt right. Any help would be greatly appreciated. Thanks!

import java.util.Random; //import random number generator
import java.io.*;
import java.util.Arrays;

public class NumGen {
	
	public static void main (String [] args)throws IOException { //creates an exception
		
		Random digit = new Random();//assigning the variable digit as a random number
		int numbers[]= new int[100];//array with 100 numbers
		File file = new File("Exercise8_19.txt");
		if (file.exists()){
			System.out.println("The file "+file.getName()+ " already exists.");
			System.out.println();
			
			
			}//ends if statement

		else {
			System.out.println("Your file has been written to " + (file.getName()+ "."));
			System.out.println();
		}
		try {
			   Writer output = null;
			   
			    File x = new File("Exercise8_19.txt");//name of txt file
			    output = new BufferedWriter(new FileWriter(x));
			  
			       
			for (int i=0; i<numbers.length; i++){//for loop to create 100 random numbers
			 numbers[i] = (digit.nextInt (100));//set the array to the random numbers with a range of 0 - 100
			 Arrays.sort(numbers);
			 output.write(numbers[i]+" ");//output is the array of random numbers separated by a space
			}//ends for loop
			output.close();//ends output
			
			FileInputStream fstream = new FileInputStream("Exercise8_19.txt");
			 // Get the object of DataInputStream
			    DataInputStream in = new DataInputStream(fstream);
			        BufferedReader br = new BufferedReader(new InputStreamReader(in));
			    String strLine;
			    //Read File Line By Line
			    while ((strLine = br.readLine()) != null)   {
			      // Print the content on the console
			      System.out.println (strLine);
			    }
			    //Close the input stream
			    in.close();
		   }//ends try 
		   catch (IOException e) {// if there is no file
				System.err.println("The file was not saved.");//error message
				e.printStackTrace();
				}//ends catch
		
		   
		
	}//ends main

}//ends class

Edited 6 Years Ago by bymak87: n/a

You need first to populate all the array and then sort. What you do is this:

for () {
 array[i] = number;
 sort;  
}

But with that you put the first number and you sort an array that has only 1 number. Then you add a second number and again you sort an almost empty array.
First finish with populating the array with all the numbers and then sort the full array.

When you say you get a lot of zeros when that happens? What is saved in the file? What is printed.

Also I think that you should write your own sorting method. But you'd better ask your teacher if you can use the Array.sort method or write your own.

Ok. I wrote a method for a selction sort. That didnt help either.When I don't sort the array I get an array with 100 numbers all random. But when I try to sort the array, I get an unusual amount of zeros.
]0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 17 21 21 24 31 31 39 41 43 43 43 53 53 56 56 56 56 65 65 65 65 69 70 70 70 70 78 78 78 78 81 81 81 81 81 81 90 90 90 90 90 90 94 94 94 94 94 94 98

when I don't sort
63 44 55 83 71 93 91 95 62 97 12 57 7 35 50 30 49 41 84 10 4 54 56 50 68 59 27 34 63 79 76 95 46 55 57 14 33 4 47 15 84 76 4 52 23 21 82 86 4 98 25 26 72 44 18 71 48 81 40 55 16 48 81 56 59 0 63 77 57 66 0 5 96 42 99 85 5 70 32 57 56 51 88 5 64 51 47 30 7 80 91 45 32 10 98 41 15 90 96 64

Edited 6 Years Ago by bymak87: n/a

You need first to populate all the array and then sort. What you do is this:

for () {
 array[i] = number;
 sort;  
}

But with that you put the first number and you sort an array that has only 1 number. Then you add a second number and again you sort an almost empty array.
First finish with populating the array with all the numbers and then sort the full array.

When you say you get a lot of zeros when that happens? What is saved in the file? What is printed.

Also I think that you should write your own sorting method. But you'd better ask your teacher if you can use the Array.sort method or write your own.

Ok. I wrote a method for a selction sort. That didnt help either.When I don't sort the array I get an array with 100 numbers all random. But when I try to sort the array, I get an unusual amount of zeros.
]0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 17 21 21 24 31 31 39 41 43 43 43 53 53 56 56 56 56 65 65 65 65 69 70 70 70 70 78 78 78 78 81 81 81 81 81 81 90 90 90 90 90 90 94 94 94 94 94 94 98

when I don't sort
63 44 55 83 71 93 91 95 62 97 12 57 7 35 50 30 49 41 84 10 4 54 56 50 68 59 27 34 63 79 76 95 46 55 57 14 33 4 47 15 84 76 4 52 23 21 82 86 4 98 25 26 72 44 18 71 48 81 40 55 16 48 81 56 59 0 63 77 57 66 0 5 96 42 99 85 5 70 32 57 56 51 88 5 64 51 47 30 7 80 91 45 32 10 98 41 15 90 96 64
Last edited by bymak87; 5 Minutes Ago at 5:20 am.

In that case, I would assume that there is something wrong with the sort method.
Write a small program in another class:

class Test {
 public static void main(String [] args) {
   int [] array = { 
    63, 44, 55, 83, 71, 93, 91, 95, 62, 97, 12, 57, 7, 35, 50, 30, 49, 41
     /* put here the numbers you want to sort */ 
   };
   // call the sort method
   // print the array
 }
}

Check if the sort method works. Post the code of the sort method as well as the results of the above code

Here is a copy of the code i used:

public static class SelectionSort{
	      static void selectionSort(int list[]){
	    	  for (int i=0; i<list.length-1; i++){
	    		  int currentMin = list[i];
	    		  int currentMinIndex = i;
	    		  
	    		  for( int j = i+1; j< list.length-1; j++){
	    			  if (currentMin > list[j]){
	    				  currentMin = list[j];
	    				  currentMinIndex= j;
	    			  }
	    		  }
	    		  if (currentMinIndex != i){
	    			  list[currentMinIndex]=list[i];
	    			  list[i]= currentMin;
	    			  
	    			  }
	    		  }
	    	  }

It is the same result as the Arrays.sort, which I am able to use.

I think I can assume what the problem is. Do you do the sorting in the for loop? If yes here is what happens.

for () {
  number[i] = random;
  sort;
}

First of all when you create the array all of its elements are zero.
When you sort you rearrange the elements of the array. So when you try to add the second random number it is being put at the second position of the sorted array, not after the previous number.

Array = {0,0,0,0,0}
Adding number = {5,0,0,0,0} // i = 0
Sorting = {0,0,0,0,5}

Array = {0,0,0,0,5}
Adding number = {0,2,0,0,5} // i = 1
Sorting = {0,0,0,2,5}

Array = {0,0,0,2,5}
Adding number = {0,0,4,2,5} // i = 2
Sorting = {0,0,2,4,5}

If you keep this up, the initial values you entered will be overridden by the new ones you added:

Array = {0,0,2,4,5} // adding the next number at the i=3
Adding number = {0,0,2,8,5} // i = 3 // the 4 is gone
Sorting = {0,0,2,8,5} // and the zeros are still there


Array = {0,0,2,8,5} // adding the next number at the i=4
Adding number = {0,0,2,8,1} // i = 4 // the 5 is gone
Sorting = {0,0,1,2,8} // and the zeros are still there

Are you saying i should sort after the for loop? That didnt sort the numbers.

import java.util.Random; //import random number generator
import java.io.*;


public class NumGen {
	
	public static void main (String [] args)throws IOException { //creates an exception
		
		Random digit = new Random();//assigning the variable digit as a random number
		int list[]= new int[100];//array with 100 numbers
		File file = new File("Exercise8_19.txt");
		
		if (file.exists()){
			System.out.println("The file "+file.getName()+ " already exists.");
			System.out.println();
			
			
			}//ends if statement

		else {
			System.out.println("Your file has been written to " + (file.getName()+ "."));
			System.out.println();
		}
		try {
			   Writer output = null;
			   
			    File x = new File("Exercise8_19.txt");//name of txt file
			    output = new BufferedWriter(new FileWriter(x));
			  
			       
			for (int i=0; i<list.length; i++){//for loop to create 100 random numbers
				list[i] = (digit.nextInt (100));//set the array to the random numbers with a range of 0 - 100
			 
					 
			
			 output.write(list[i]+" ");//output is the array of random numbers separated by a space
			}//ends for loop
			SelectionSort.selectionSort(list);

			output.close();//ends output
			
			FileInputStream fstream = new FileInputStream("Exercise8_19.txt");
			 // Get the object of DataInputStream
			    DataInputStream in = new DataInputStream(fstream);
			        BufferedReader br = new BufferedReader(new InputStreamReader(in));
			    String strLine;
			    //Read File Line By Line
			    while ((strLine = br.readLine()) != null)   {
			      // Print the content on the console
			      System.out.println (strLine);
			    }
			    //Close the input stream
			    in.close();
		   }//ends try 
		   catch (IOException e) {// if there is no file
				System.err.println("The file was not saved.");//error message
				e.printStackTrace();
				}//ends catch
		
		   
		
	}//ends main
//Selction sort method
	  public static class SelectionSort{
	      static void selectionSort(int list[]){
	    	  for (int i=0; i<list.length-1; i++){
	    		  int currentMin = list[i];
	    		  int currentMinIndex = i;
	    		  
	    		  for( int j = i+1; j< list.length-1; j++){
	    			  if (currentMin > list[j]){
	    				  currentMin = list[j];
	    				  currentMinIndex= j;
	    			  }
	    		  }
	    		  if (currentMinIndex != i){
	    			  list[currentMinIndex]=list[i];
	    			  list[i]= currentMin;
	    			  
	    			  }
	    		  }
	    	  }
	  
	      }
	  
}//ends class

Edited 6 Years Ago by bymak87: n/a

Yes, after the loop.

First of all if you do it in the loop, the array starts like this: {0,0,0,...
Then you put the 0th element: {3,0,0,.. If you sort that 3 will go at the end of the array.
So after the sort you have: {0,0,0,......,3}. Then you will put the 1th element at the i position: {0,5,0,... If you do that you are stuck with a zero at the 0th position. Nothing will change that because you keep adding elements at the 2nd, 3rd. That zero and the other zeros are there to stay.

Also if you do the sorting in the loop you will be calling that method 100 times. Why call the sort 100 times, when you can call it once after you have the array ready.

Also the array has been sorted. There is no doubt about that. But you don't save the sorted array in the file:

for () {
  get random number;
  write to file (unsorted);
}
sort array;

The numbers saved to the file are unsorted, but the array is.

Now what do you want?
Do you want to sort the array? Do you want to save the unsorted array? Do you want to save the sorted array? Do you want to save both?

Ok I figured it out. Thanks for your help!!

Edited 6 Years Ago by bymak87: n/a

Is it so difficult to have a second loop?

for () {
  read random numbers into the array;
}

sort the array;

for (loop the sorted array) {
  output.write(list[i]+" "); // save the sorted array
}

output.close();

Edited 6 Years Ago by javaAddict: n/a

you can also try this sorting algorithm

import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
    ArrayList<AffineTransform> affs;
    ListIterator<AffineTransform> li;
    Integer count, count2;
    /**
     * @param args
     */
    public static void main(String[] args) {
        new QuicksortAlgorithm();
    }
    public QuicksortAlgorithm(){
        count = new Integer(0);
        count2 = new Integer(1);
        affs = new ArrayList<AffineTransform>();
        for (int i = 0; i <= 128; i++){
            affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
        }
        affs = arrangeNumbers(affs);
        printNumbers();
    }
    public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
        while (list.size() > 1 && count != list.size() - 1){
            if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
                list.add(count, list.get(count2));
                list.remove(count2 + 1);
            }
            if (count2 == list.size() - 1){
                count++;
                count2 = count + 1;
            }
            else{
            count2++;
            }
        }
        return list;
    }
    public void printNumbers(){
        li = affs.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
    }
}
This question has already been answered. Start a new discussion instead.