Solved

array

Posted on 2009-05-04
32
250 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
ID: 24301249
0
 

Author Comment

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

Expert Comment

by:objects
ID: 24301901
0
 

Author Comment

by:Sdurrani
ID: 24321068
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
ID: 24321318
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
ID: 24321350
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
ID: 24321354
> class Numbers {

should be a public class

public class Numbers {


0
 

Author Comment

by:Sdurrani
ID: 24321395
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
ID: 24321549
its not sorting what am i missing here
0
 
LVL 92

Expert Comment

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

0
 

Author Comment

by:Sdurrani
ID: 24321611
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
ID: 24321662
see the link I posted earlier, show you how to generate a random number

0
 

Author Comment

by:Sdurrani
ID: 24321687
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
ID: 24321770
that just creates the generator, you then use it to generate random numbers


0
 

Author Comment

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

Expert Comment

by:objects
ID: 24321827
int random = generator.nextInt(100) + 1;

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

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

Expert Comment

by:objects
ID: 24321864
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
ID: 24332373
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
ID: 24332380
the numbers are in sequential order and NOT random ..
0
 
LVL 92

Expert Comment

by:objects
ID: 24332383
>         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
ID: 24332571
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
ID: 24332847
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
ID: 24333058
>       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
ID: 24335811
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
ID: 24336792
is there anyone else who can help me??????
0
 

Author Comment

by:Sdurrani
ID: 24337243
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
ID: 24339883
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
ID: 24340500
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
ID: 24340561
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
ID: 24341160
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
ID: 24341303
Where woudl the PrintWriter go ????
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
groovy example issue 10 90
ArrayIndexOutOfBoundException 9 68
servlet requestdispatcher include and forward differences 1 25
fibonacci ten numbers 4 28
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
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:

895 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

16 Experts available now in Live!

Get 1:1 Help Now