Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: ReadWrite program advise

  1. #1
    Member Java Neil's Avatar
    Join Date
    Jan 2011
    Posts
    72
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default ReadWrite program advise

    Hi all...I have this program that I wrote that creates a random number, writes it to a file and scans it back to the system. That part alone took me forever to hash out. Now I stuck. I would like to create 100 random integers and sort them in both the file and the printout.

    Here is the code

       import java.util.Random;
       import java.util.Scanner;
       public class ReadWriteData {
     
        // Main method
          public static void main (String[] args)throws Exception {
     
           //Create a file instance
             java.io.File file = new java.io.File("100 random  sorted numbers txt.");
     
             if (file.exists()) {
                System.out.println("File Already Exists");
                System.exit(0);
     
             }
     
             //Create a file
             java.io.PrintWriter output = new java.io.PrintWriter(file);
     
          	//Create ramdom number to be sorted
             Random randomGenerator = new Random();
     
             //Write formatted output to the file
             output.println(randomGenerator.nextInt(100));
     
             //close the output file
             output.close();
     
             //Create a Scanner for the file
             Scanner input = new Scanner(file); 
     
             //Read data from a file
             while (input.hasNext()) {
     
                int score = input.nextInt();
                System.out.println(
                      score);
             }
     
             //Close the input file
             input.close();    
          }
       }

    Could someone advise me on the logic and code placement needed to pull this off?


  2. #2
    Member Java Neil's Avatar
    Join Date
    Jan 2011
    Posts
    72
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: ReadWrite program advise

    Well I corrected my code to print and write 100 integers. On the other hand I'm completely stumped about how to sort it. Help me please!

    Do I need an array? Where should that code go if I do? If not, then what?

       import java.util.Random;
       import java.util.Scanner;
       public class ReadWriteData {
     
        // Main method
          public static void main (String[] args)throws Exception {
     
           //Create a file instance
             java.io.File file = new java.io.File("100 random  sorted numbers txt.");
     
             if (file.exists()) {
                System.out.println("File Already Exists");
                System.exit(0);
     
             }
     
             //Create a file
             java.io.PrintWriter output = new java.io.PrintWriter(file);
     
          	//Create ramdom number to be sorted
             Random randomGenerator = new Random();
     
             for (int i = 0; i < 100; i++) {
     
             //Write formatted output to the file
                output.println(randomGenerator.nextInt(100));
             }
     
             //close the output file
             output.close();
     
             //Create a Scanner for the file
             Scanner input = new Scanner(file); 
     
             //Read data from a file
             while (input.hasNext()) {
     
                int score = input.nextInt();
                System.out.println(
                      score);
             }
     
             //Close the input file
             input.close();    
          }
       }

  3. #3
    Member Java Neil's Avatar
    Join Date
    Jan 2011
    Posts
    72
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: ReadWrite program advise

    I'm almost there. I decided to use my own class to sort but it's not working. It might be the placement.

    Take a look...

       import java.util.Random;
       import java.io.*;
     
       public class ReadWriteSort {
     
        //Creates an exception
          public static void main (String [] args)throws IOException { 
     
           //Assigns the variable digit as a random number
             Random digit = new Random();
     
           //Array with 100 numbers
             int list[] = new int[100];
             File file = new File("Exercise9_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;
     
              //Name of txt file
                File x = new File("Exercise9_19.txt");
                output = new BufferedWriter(new FileWriter(x));
     
              //for loop to create 100 random numbers
                for (int i = 0; i < list.length; i++) {
     
                 //Set an array of random numbers with a range of 0 - 100 
                   list[i] = (digit.nextInt(100));       
     
                 //output is the array of random numbers  
                   output.write(list[i]+" "); 
     
                }//ends for loop
     
                SelectionSort.selectionSort(list);//THIS MY BE MY PROBLEM!
     
              //ends output
                output.close();
     
                FileInputStream fstream = new FileInputStream("Exercise9_19.txt");
     
             // Get the object of DataInputStream
                DataInputStream input = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(input));
                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
                input.close();
     
             }//ends try
     
                //If there is no file
                catch (IOException e) {
                   System.err.println("The file was not saved.");
                   e.printStackTrace();
     
                }//ends catch
     
          }
     
        //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

    Please show me the way of my error!

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: ReadWrite program advise

    Define 'its not working'... you've got a lot of code there that does several things so it can fail at any number of places. Break the problem down into its individual components and focus on what fails...if its the sort, then remove all else but the sort and some sample test input and go from there - post that code if you are having problems (this in other words, is the process of writing an SSCCE)

  5. #5
    Member vanDarg's Avatar
    Join Date
    Jan 2011
    Location
    Chicago
    Posts
    65
    My Mood
    Mellow
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: ReadWrite program advise

    You don't have to create a separate class for sorting an array of ints. Just write a separate method for it.
    "Everything should be made as simple as possible, but not simpler."
    Asking Questions for Dummies | The Java Tutorials | Java Coding Styling Guide

  6. #6
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: ReadWrite program advise

    1. Use list instead of array and use it's built in sort.
    2. I mean to say, first put all random numbers in the list, sort them and place them in the file.