Solved

array

Posted on 2009-05-04
32
246 Views
Last Modified: 2013-11-23
I need help writing a program in which integers are read from a file into an array and sort. .
not sure where to start

Open in new window

0
Comment
Question by:Sdurrani
  • 21
  • 11
32 Comments
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 

Author Comment

by:Sdurrani
Comment Utility
The numbers would be generated from a random number generator.
totally stuck
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 

Author Comment

by:Sdurrani
Comment Utility
Hi there
I am working on the following code below and this is what i would liek the code to do however i am not getting it to compile together. I need to write a program that would be  a number generator program that asks the user to input a file name, then goes on to generate 100 random integers and saves them in the aforementioned file THEN a program that reads a list of integers from a file into an array or some data structure - The TreeSet method was what i was using for this so that it would be easier to sort. The program should read the list thenusing a sorting algorithm of your choice (possible examples include quick sort) order the list. Once the list is ordered it should be saved to an output file. The program should prompt the user for an input and output file.

import java.util.Random;

import java.lang.Thread;

import java.io*;

import java.util.Scanner;
 

class Numbers {
 
 

public static void main (String [] args) throws Exception {

for (int i=0 ; i<100 ; i++) {

System.out.println (i+1) ;

Thread.sleep (10);

}
 

}

}

private int lineCount = 0;
 

      int findNumberOfLines(String fileName) {

            FileReader reader;

            Scanner in = null;

            try {
 

                  reader = new FileReader("");

                  in = new Scanner(reader);

                  String line = null;
 

                  while (null!=(line = in.nextLine())) {
 

                        lineCount++;

                  }

            }
 

            catch (Exception e) {
 

                  System.out.print("File cannot be found ");

                  System.exit(0);

            } finally {

                  in.close();

            }
 

            return lineCount;

      }
 

      public static void main(String[] args) {

            CountLines cl = new CountLines();

            Scanner console = new Scanner(System.in);

            System.out.println("Please enter the file name: ");

            String inputFileName = console.next();

            System.out.println("The number of lines in file " + inputFileName

                        + " is " + cl.findNumberOfLines(inputFileName) + "!");

      }

}

Open in new window

0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
Comment Utility
cleaned it up a bit, this will compile for you

import java.util.Random;
import java.lang.Thread;
import java.io.*;
import java.util.Scanner;

class Numbers {

      private int lineCount = 0;

      int findNumberOfLines(String fileName) {
            FileReader reader;
            Scanner in = null;
            try {

                  reader = new FileReader("");
                  in = new Scanner(reader);
                  String line = null;

                  while (null != (line = in.nextLine())) {

                        lineCount++;
                  }
            }

            catch (Exception e) {

                  System.out.print("File cannot be found ");
                  System.exit(0);
            } finally {
                  in.close();
            }

            return lineCount;
      }

      public static void main(String[] args) {
            Numbers cl = new Numbers();
            Scanner console = new Scanner(System.in);
            System.out.println("Please enter the file name: ");
            String inputFileName = console.next();
            
            for (int i = 0; i < 100; i++) {
                  System.out.println(i + 1);
            }

            System.out.println("The number of lines in file " + inputFileName
                        + " is " + cl.findNumberOfLines(inputFileName) + "!");
      }
}
0
 

Author Comment

by:Sdurrani
Comment Utility
Hi there
I tried to compile and run it - it compiled however i got the following error when i tried to run it

Exception in thread "main" java.lang.NoClassDefFoundError: FinalExam
Caused by: java.lang.ClassNotFoundException: FinalExam
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Press any key to continue . . .
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> class Numbers {

should be a public class

public class Numbers {


0
 

Author Comment

by:Sdurrani
Comment Utility
I haave a question as i am not an expert but is this encompassing all the things that i wrote above? sorry but if you could include some comments so that I can make notes for myself as well so i know what and how themethods were used

thank you
0
 

Author Comment

by:Sdurrani
Comment Utility
its not sorting what am i missing here
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
you haven't added any code to sort yet (or generate random numbers)

0
 

Author Comment

by:Sdurrani
Comment Utility
import java.util.Random;
import java.lang.Thread;
import java.io.*;
import java.util.Scanner;

public class FinalExam {

      private int lineCount = 0;
        Random generator = new Random();

      int findNumberOfLines(String fileName) {
            FileReader reader;
            Scanner in = null;
            try {

                  reader = new FileReader("");
                  in = new Scanner(reader);
                  String line = null;

                  while (null != (line = in.nextLine())) {

                        lineCount++;
                  }
            }

            catch (Exception e) {

                  System.out.print("File cannot be found ");
                  System.exit(0);
            } finally {
                  in.close();
            }

            return lineCount;
      }

      public static void main(String[] args) {
            Numbers cl = new Numbers();
            Scanner console = new Scanner(System.in);
            System.out.println("Please enter the file name: ");
            String inputFileName = console.next();

            for (int i = 0; i < 100; i++) {
                  System.out.println(i + 1);
            }

            System.out.println("The number of lines in file " + inputFileName
                        + " is " + cl.findNumberOfLines(inputFileName) + "!");
      }
}// the numbers are still coming out in order.. help
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
see the link I posted earlier, show you how to generate a random number

0
 

Author Comment

by:Sdurrani
Comment Utility
i did the following

      private int lineCount = 0;
        Random generator = new Random();

following what the link you sent earlier.. please advise
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
that just creates the generator, you then use it to generate random numbers


0
 

Author Comment

by:Sdurrani
Comment Utility
lost/... sorry i really struggle wiht java..its like i learn something and then its gone....
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
int random = generator.nextInt(100) + 1;

0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:Sdurrani
Comment Utility
how does a user save theoutput  based on the code above?
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
use something like this

PrintWriter out = new PrintWriter(new FileWriter("out.txt"));
for (int i = 0; i < 100; i++) {
       out.println(generator.nextInt(100) + 1);
}
out.close();


0
 

Author Comment

by:Sdurrani
Comment Utility
import java.util.Random;
import java.lang.Thread;
import java.io.*;
import java.util.Scanner;

public class FinalExam {

      private int lineCount = 0;
      Random generator = new Random();
        int random = generator.nextInt(100) + 1;


      int findNumberOfLines(String fileName) {
            FileReader reader;
            FileWriter writer;
            Scanner in = null;
            try {

                  reader = new FileReader("");
                  in = new Scanner(reader);
                  String line = null;

                  while (null != (line = in.nextLine())) {

                        lineCount++;
                  }
            }

            catch (Exception e) {

                  System.out.print("File cannot be found ");
                  System.exit(0);
            } finally {
                  in.close();
            }

            return lineCount;
      }

      public static void main(String[] args) {
            Numbers cl = new Numbers();
            Scanner console = new Scanner(System.in);
            System.out.println("Please enter the file name: ");
            String inputFileName = console.next();

            for (int i = 0; i < 100; i++) {
                  System.out.println(i + 1);
            }

            System.out.println("The number of lines in file " + inputFileName
                        + " is " + cl.findNumberOfLines(inputFileName) + "!");
      }
}//// Help its not doing what i need it to do ... write a program that would be  a number generator program that asks the user to input a file name, then goes on to generate 100 random integers and saves them in the aforementioned file THEN a program that reads a list of integers from a file into an array or some data structure - The TreeSet method was what i was using for this so that it would be easier to sort. The program should read the list thenusing a sorting algorithm of your choice (possible examples include quick sort) order the list. Once the list is ordered it should be saved to an output file. The program should prompt the user for an input and output file.
0
 

Author Comment

by:Sdurrani
Comment Utility
the numbers are in sequential order and NOT random ..
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
>         int random = generator.nextInt(100) + 1;

thats in the wrong place, move it inside your loop

            for (int i = 0; i < 100; i++) {
                  int random = generator.nextInt(100) + 1;
                  System.out.println(random);
            }

0
 

Author Comment

by:Sdurrani
Comment Utility
Hi there
When i did move that section into the for loop I got the following error..

FinalExam.java:47: non-static variable generator cannot be referenced from a static context
                        int random = generator.nextInt(100) + 1;
0
 

Author Comment

by:Sdurrani
Comment Utility
I really need some help here.. i am totally confused right now .. its like I am trying these things and nothing seems to be working how i need it to work .. HELP ..I am new to Java and really need step by step instructions or coding help

1.) I need to write a program that would be  a number generator program that asks the user to input a file name,//this part i think is done please correct me if i am wrong

2.) Then the program  then goes on to generate 100 random integers and saves them in the aforementioned file //the numbers are coming out in sequential order ( 1,2, 3, 4, etx,,, not 1, 4 , 5, 8, etx)

3.) Another program that would that reads the list of integers from a file into an array or some data structure// - The TreeSet method was what i was using for this so that it would be easier to sort.

 The program should read the list then using a sorting algorithm of your choice (possible examples include quick sort) order the list. Once the list is ordered it should be saved to an output file. The program should prompt the user for an input and output file.

I am not sure if the following code is going to do what i need it to do
import java.util.Random;

import java.lang.Thread;

import java.io.*;

import java.util.Scanner;
 

public class FinalExam {
 

      private int lineCount = 0;

      Random generator = new Random();
 
 
 

      int findNumberOfLines(String fileName) {

            FileReader reader;

            FileWriter writer;

            Scanner in = null;

            try {
 

                  reader = new FileReader("");

                  in = new Scanner(reader);

                  String line = null;
 

                  while (null != (line = in.nextLine())) {
 

                        lineCount++;

                  }

            }
 

            catch (Exception e) {
 

                  System.out.print("File cannot be found ");

                  System.exit(0);

            } finally {

                  in.close();

            }
 

            return lineCount;

      }
 

      public static void main(String[] args) {

            Numbers cl = new Numbers();

            Scanner console = new Scanner(System.in);

            System.out.println("Please enter the file name: ");

            String inputFileName = console.next();
 

              for (int i = 0; i < 100; i++) {

			                  int random = generator.nextInt(100) + 1;

			                  System.out.println(random);

			            }
 

			 private void execute() {

			        testSort(generateArray(10000), RUN_TENK);

			        testSort(generateArray(100000), RUN_HUNDREDK);

			        testSort(generateArray(1000000), RUN_THOUSANDK);

			        printReport();

    }

            System.out.println("The number of lines in file " + inputFileName

                        + " is " + cl.findNumberOfLines(inputFileName) + "!");

      }

}

Open in new window

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
>       Random generator = new Random();

move that into main

      Random generator = new Random();
              for (int i = 0; i < 100; i++) {
                                          int random = generator.nextInt(100) + 1;
                                          System.out.println(random);
                                    }

0
 

Author Comment

by:Sdurrani
Comment Utility
Hi there
after moving that into the main i received the following error message ]

SDurrani\My Documents\FinalExam.java:51: illegal start of expression
                         private void execute() {
                         ^
C:\Documents and Settings\SDurrani\My Documents\FinalExam.java:51: illegal start of expression
                         private void execute() {
                                 ^
C:\Documents and Settings\SDurrani\My Documents\FinalExam.java:51: ';' expected
                         private void execute() {
                                             ^
0
 

Author Comment

by:Sdurrani
Comment Utility
is there anyone else who can help me??????
0
 

Author Comment

by:Sdurrani
Comment Utility
why am i getting this error

C:\Documents and Settings\SDurrani\My Documents\FinalExam.java:51: ';' expected
                         private void execute() {
                                             ^

i have done what it stated but still the same error shows up
0
 

Author Comment

by:Sdurrani
Comment Utility
Hi there
I tried to attempt to save the output from the code and i got the following errors - what do they mean

ocuments and Settings\SDurrani\My Documents\Numbers.java:57: not a statement
                  DataOutputStream do = new DataOutputStrean(fo);
                  ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:57: ';' expected
                  DataOutputStream do = new DataOutputStrean(fo);
                                  ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:57: illegal start of expression
                  DataOutputStream do = new DataOutputStrean(fo);
                                      ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:57: while expected
                  DataOutputStream do = new DataOutputStrean(fo);
                                                                 ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:59: illegal start of expression
                  do.writeChars(theStringToWrite);
                    ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:59: ')' expected
                  do.writeChars(theStringToWrite);
                     ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:59: ';' expected
                  do.writeChars(theStringToWrite);
                               ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:59: not a statement
                  do.writeChars(theStringToWrite);
                                ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:59: ';' expected
                  do.writeChars(theStringToWrite);
                                                ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:61: illegal start of expression
                  do.close();
                    ^
C:\Documents and Settings\SDurrani\My Documents\Numbers.java:61: while expected
                  do.close();
                     ^
C:\Documents and Settings\SDurrani\My Docume
import java.util.Random;

import java.lang.Thread;

import java.io.*;

import java.util.Scanner;
 

class Numbers {
 

      private int lineCount = 0;
 

      int findNumberOfLines(String fileName) {

            FileReader reader;

            Scanner in = null;

            try {
 

                  reader = new FileReader("");

                  in = new Scanner(reader);

                  String line = null;
 

                  while (null != (line = in.nextLine())) {
 

                        lineCount++;

                  }

            }
 

            catch (Exception e) {
 

                  System.out.print("File cannot be found ");

                  System.exit(0);

            } finally {

                  in.close();

            }
 

            return lineCount;

      }
 

      public static void main(String[] args) {

            Numbers cl = new Numbers();

            Scanner console = new Scanner(System.in);

            System.out.println("Please enter the file name: ");

            String inputFileName = console.next();
 

            Random generator = new Random();

            for (int i = 0; i < 1000; i++) {

            System.out.println(i + 1);

            }
 

			File theFile = new File("fikle/lcoation");

			if (theFile.exists())

			theFile.delete();

			theFile.createNewFile();
 

			//This will create a new file, overwriting any file that existsed before.
 

			//in order to write to the file, I used use the following:
 

			FileOutpStream fo = new FIleOutputStream(theFile);

			DataOutputStream do = new DataOutputStrean(fo);
 

			do.writeChars(theStringToWrite);
 

			do.close();

			fo.close();
 
 
 

            System.out.println("The number of lines in file " + inputFileName

                        + " is " + cl.findNumberOfLines(inputFileName) + "!");

      }

}

Open in new window

0
 

Author Comment

by:Sdurrani
Comment Utility
import java.util.Random;
import java.lang.Thread;
import java.io.*;
import java.util.Scanner;

public class FinalExam {

      private int lineCount = 0;



      int findNumberOfLines(String fileName) {
            FileReader reader;
            FileWriter writer;
            Scanner in = null;
            try {

                  reader = new FileReader("");
                  in = new Scanner(reader);
                  String line = null;

                  while (null != (line = in.nextLine())) {

                        lineCount++;
                  }
            }

            catch (Exception e) {

                  System.out.print("File cannot be found ");
                  System.exit(0);
            } finally {
                  in.close();
            }

            return lineCount;
      }

      public static void main(String[] args) {
            Numbers cl = new Numbers();
            Scanner console = new Scanner(System.in);
            System.out.println("Please enter the file name: ");
            String inputFileName = console.next();

                  Random generator = new Random();
              for (int i = 0; i < 100; i++) {
                                    int random = generator.nextInt(100) + 1;
                                    System.out.println(random);
                              }

                                    File theFile = new File("file/lcoation");
                              if (theFile.exists()  );
                                          catch (IOException e)
                              theFile.delete();
                              theFile.createNewFile();

                        //This will create a new file, overwriting any file that existsed before.

                        //in order to write to the file, I used use the following:











      }
}
0
 

Author Comment

by:Sdurrani
Comment Utility
I am getitng an IOexceoption error- how do i write the code so that it can take the name of whatever file the user types in
0
 

Author Comment

by:Sdurrani
Comment Utility
OK so i think i got it now - the numbers are completely random like i needed them to be however when i use the PrintWriter command as recommeneded above I get some IO error please see the code below and let me know where I would need to insert the print Write command so that output - random number sequence can be saved


import java.util.Random;

//this is DONE - the numbers are random just need to figure out how to save them to the file

import java.lang.Thread;

import java.io.*;

import java.util.Scanner;
 

public class FinalExam {
 

      private int lineCount = 0;
 
 
 

      int findNumberOfLines(String fileName) {

            FileReader reader;

            FileWriter writer;

            Scanner in = null;

            try {
 

                  reader = new FileReader("");

                  in = new Scanner(reader);

                  String line = null;
 

                  while (null != (line = in.nextLine())) {
 

                        lineCount++;

                  }

            }
 

            catch (Exception e) {
 

                  System.out.print("File cannot be found ");

                  System.exit(0);

            } finally {

                  in.close();

            }
 

            return lineCount;

      }
 

      public static void main(String[] args) {

            Numbers cl = new Numbers();

            Scanner console = new Scanner(System.in);

            System.out.println("Please enter the file name: ");

            String inputFileName = console.next();
 

                  Random generator = new Random();

              for (int i = 0; i < 100; i++) {

                                    int random = generator.nextInt(100) + 1;

                                    System.out.println(random);

                              }
 
 
 

      }

}

Open in new window

0
 

Author Comment

by:Sdurrani
Comment Utility
Where woudl the PrintWriter go ????
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now