Link to home
Start Free TrialLog in
Avatar of SeanBarton13
SeanBarton13

asked on

help need quick answer

i am writing a java program to receive text from a csv file and split it up into tokens (got a string tokenizer working ok). i am now working on a series of IF statements to receive the tokenized csv information and split it up into several array. i only need the 9th column called marks.

2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10001,,#87,59,,,10001

i need to get hold of the 59 to the right of the line. here is my code so far.

import java.io.*;          //import necessary libraries for things like tokenizer
import java.util.*;

public class reader
{

  public static void main(String args[])
  {

  //declare global variables

    String arr1[] = new String[]{};
    String arr2[] = new String[]{};
    String arr3[] = new String[]{};
    String arr4[] = new String[]{};
    String arr5[] = new String[]{};
    String arr6[] = new String[]{};
    String arr7[] = new String[]{};
    String arr8[] = new String[]{};
    String arr9[] = new String[]{};
    String arr10[] = new String[]{};

    String line;
    String year;

    try //file import code
    {
      File inFile = new File("marks.csv");  //create object linked to actual file
      FileReader reader = new FileReader(inFile); //create input stream
      BufferedReader buff = new BufferedReader(reader);

      line = buff.readLine(); //read first line
      //while (line != null)  //null returned when no more to read
      //{

       System.out.println(line);
       line = buff.readLine(); //get next
       year = line;

      //}

      //tokenizing code

      StringTokenizer st = new StringTokenizer(year,",");

      String arr[] = new String[st.countTokens()];

      // below is code to tokenize the string called st at the , mark and output to screen

      for (int i = 0; st.hasMoreTokens(); i++)
      {
          arr[i]= st.nextToken();

          //System.out.println (arr[i]);

          EasyIn.pause();
          if (i == 0)
          {

            arr1[i] = st.nextToken();

            System.out.println("------------this shud be correct------------");
            System.out.println(arr1[i]);
          }
          if (i == 1)
          {

          arr2[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr2[i]);
          }
          if (i == 2)
          {

          arr3[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr3[i]);
          }
          if (i == 3)
          {

          arr4[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr4[i]);
          }
          if (i == 4)
          {

          arr5[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr5[i]);
          }
          if (i == 5)
          {

          arr6[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr6[i]);
          }
          if (i == 6)
          {

          arr7[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr7[i]);
          }
          if (i == 7)
          {

          arr8[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr8[i]);
          }
          if (i == 8)
          {

          arr9[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr9[i]);
          }
          if (i == 9)
          {

          arr10[i] = st.nextToken();

          System.out.println("------------this shud be correct------------");
          System.out.println(arr10[i]);
        }
      }
    }

    catch(IOException e)
    {
      System.out.println("error has occured: "+e);
    }
  }
}


as you can see it is a bit of a work in progress!! if i take out the if statements then it works fine. although it does compile with the if's in, when i try and run it i get a window up which instantly disappears

please reply soon... i really need help

Sean
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

>>when i try and run it i get a window up which instantly disappears

Sounds like you may be running using javaw. If so, just use java
Avatar of SeanBarton
SeanBarton

whats that then?

i am fairly new to java and have got a copy of jbuilder3 from a friend.. where can i get java from? if not is there no other method i can sort this problem out

Sean
Unless you're quite experienced, i'd recommend NOT using an IDE. Get used to working at the command line, or you won't learn Java from first principles properly.
its ok im used to using an IDE...i have written quite a few programs in them before...i am just working through examples in my book. i am experimenting with string tokenizer which i got working (using other peoples questions on this i might add) but i find it strange how whenever i add an if statement into a working program (which i hope makes sense) it fails on me...

can you suggest how i sort my if statements so they do what i want them to...if not please can you maybe tell me of another way of doing what i am trying to accoplish (because lets face it, its not the most efficient way is it?)

Sean
The thing is, you haven't said *how* it fails. Is there an exception? What is the stack trace?
>>arr[i]= st.nextToken();

This and similar statements won't work - at that point, that array has length 0
you see this is the problem... from what i see i get an exception of some kind... i click compile and run then a console window comes up, runs the program and then closes itself... i have tried putting easyin.pauses in everywhere to try and find exactly where the problem is and every time it fails at the first if statement:

if (i == 0)
          {

            arr1[i] = st.nextToken();                       -- it fails here usually.

            System.out.println("------------this shud be correct------------");
            System.out.println(arr1[i]);
          }

Sean
>>from what i see i get an exception of some kind...

This is a case in point of what i was talking about above. If you were running in a console, there would be no doubt about it, or what the exception is. You are letting the IDE control what you can and can't see - that's just going to make your job more difficult.

>>arr1[i] = st.nextToken();                       -- it fails here usually.

See my comment above
funny you diagnosed my probkem before i could post it.

i understand what you are saying. so saying that, can you suggest a way of rectififying it please.. this is the most logical way (to me) of doing it.

i dont see any other way of clearing the            arr[i] variable... i am realy trying to find a way of sorting the 10 comma'd sections in the csv file into 10 separate arrays in my program

Sean
ok then  please tell me a quick way of accessing and running my file called reader.java in a console

Sean
How big does that array need to be? Just size it accordingly:

final int REQUIRED_SIZE = 10;

String arr1[] = new String[REQUIRED_SIZE];

>>ok then  please tell me a quick way of accessing and running my file called reader.java in a console


C:\somedir>java reader
(where somedir is the directory containing class 'reader')
ok now im getting somewhere thankyou very much... the program still finishes early but i am going in the right direction.

the fifth time i press enter the program fails

any ideas?
What's the stack trace from the console?

Can you say a bit more about what you're attempting to do? - you're only interested in the 9th column etc..
Avatar of SeanBarton13

ASKER

i am trying to handle the data form the file but i only need the 9th row. iwill include some more of the csv file for you:

2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10001,,#87,59,,,10001
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10002,,#35,0,,,10002
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10003,,#87,65,,,10003
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10004,,#68,0,,,10004
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10005,,#51,85,,,10005
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10006,,#94,0,,,10006

this is the raw data stored in a file called marks.csv... i need to break this down to the marks bit which is the 59,0,65,0,85,0

if you see my code you will unerstand what i am treying to do by loking at the commented out bits... i am using a buffer and a line at a time method of reading the file... i am going to read the file line by line filling up arrays as i go... eventually when the loop completes i will be left with 8 useless arrays and one decent one with the information ready for manipulation.....(i have to do a frequency table and work out the mean average)

btw thx for telling me how to access this from the command line...it makes my life a whole lot easier

dont suppose you can tell me how i can mod this program to accept the filename as a command line argument... i will ajust the points value appropriately if you can help if not i will put as a separate question another day

Sean
Are you sure you need to use StringTokenizer? Sometimes it's overkill.

Here's an alternative:

import java.util.ArrayList;

public class CVSRow {

      private ArrayList tokens = new ArrayList();

      public CVSRow(String s) {
            String terminatedString = s + ",";
            int col = 0;
            int comma = 0;
            while ((comma = terminatedString.indexOf(',', comma + 1)) != -1) {
                  int terminatingComma = terminatedString.indexOf(',', comma + 1);
                  if (terminatingComma != -1) {
                        String token = terminatedString.substring(comma + 1, terminatingComma);
                        tokens.add(col++, token);
                  }
            }
      }

      public String getCol(int col) {
            if (col >= tokens.size())
                  return null;
            return (String) tokens.get(col);
      }

      public static void main(String[] args) {
            CVSRow row = new CVSRow("2003/4,,SEM1,CSD1005C,C99,CSD1005C,#010,10001,,#87,59,,,10001");
            int col = 0;
            String colValue;
            while ((colValue = row.getCol(col)) != null)
                  System.out.println(col++ + ": '" + colValue + "'");
      }
}
P.S. This is a classic job for Perl.
>>dont suppose you can tell me how i can mod this program to accept the filename as a command line argument

Just change

>>File inFile = new File("marks.csv");  

to

File inFile = new File(args[0]);  
see this helps but i see you have input the line as opposed to receiving it form a file...if you read the above comments you will see that i am quite new to java and am trying to understsand it as i go... thankyou for handing me the code on a plate but i dont understand any of it... CEHJ has been helping me mod my code bit by bit so i understand it so i will try and get that to work first... thankyou for the code though...im sure when iget a bit better i will understand it

Sean
If you've got the line from reading the file (which you have) using a regex is even easier:

// before the loop
ArrayList tokens = new ArrayList();
final String RE = ".*?,.*?,.*?,.*?,.*?,.*?,.*?,.*?,(.*?).+";
Pattern pat = Pattern.compile(RE);

// in the loop
Matcher mat = pat.matcher(line);
if (mat.matches()) {
      tokens.add(mat.group(1).trim());
}
Whoops

>>final String RE = ".*?,.*?,.*?,.*?,.*?,.*?,.*?,.*?,(.*?).+";

should be

final String RE = ".*?,.*?,.*?,.*?,.*?,.*?,.*?,.*?,(.*?),.+";
ok so do i add this to my current code? what is this replacing...will this cancel the need for the 10arrays?? can u tell me whati have to comment/delete form the code and where in my loop i have to put it (if statements of before?)

Sean
SeanBarton == SeanBarton13

>>ok so do i add this to my current code?

Well first of all, let's decide what your code is designed to do. The code i just posted will collect together all the ninth column values - nothing more
yes thats me...or was...i forgot my password so i created a neew accnt...notice the time difference between postings

CEHJ can you help me with those questions?
just testing now
Make sure you delete one of those accounts. See my comments above
this is the only accnt i am using in future
Still the other must be deleted
Hi SeanBarton & SeanBarton13,

You can simply try this:


    int i=-1,n=9,j=i;
    // find the first 9 words separated by comma :
    while ( (n-->0) &&  ( (i=line.indexOf(',',i+1))>=0 ) )
    {
       token( n, line.substring(j+1,i).trim() );
       j=i;
    }
    if (n-->0) token( n, line.substring(j+1).trim() );



    void token( int n , String t )
    {
         //  n = number of remaing tokens (8 to 0)
         //  t = word
         switch ( n )
         {
            case 8 :
                // ...
                break;
            case 7 :
                // ...
                break;
            case 6 :
                // ...
                break;
            case 5 :
                // ...
                break;
            case 4 :
                // ...
                break;
            case 3 :
                // ...
                break;
            case 2 :
                // ...
                break;
            case 1 :
                // ...
                break;
            case 0 :
                // ...
                break;
         }
    }

my ide doesnt like pattern. its gone red which is uaually bad. is there an extra import for this?
ok webstorm... where does it store each of the values? your way looks simple enough but i am looking for a way of moulding this into my code

i only need the 9th column across... CEHJ has suggested a quite simple looking way of doing it but has an error

now ive got an error on matcher aswell

im getting there...
This means you probably have an old version of Java. You should probably update it or you'll be missing a lot of functionality if you're running < 1.4

ok your right... immgonna downloas the new java now... do i want the se or the sdk? and i take it 1.5 beta is ok? i will wait for the next response and come back tommorrow when i have got the new version

Sean

ps:will sort points tomorrow as the program is semi fixed but not yet working
Again, if your IDE did not hide these things from you, you'd know straight away what version of Java you're running
You just have to move the code in your " if (i == ...) " to the " case ... : "

>>and i take it 1.5 beta is ok?

I wouldn't at this stage - take the 1.4 version
i realise that and since you told me how to i have been using the console... do i need the jse or sdk please?
Always let the existing standard libraries make up as much of the code as possible unlessyou have an extremely good reason for not doing so. Here's how to do it with the Pattern:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

public class ReadNinth {

      public ReadNinth() { }

      // Read the ninth csv column
      public List collectTokens(String fileName) throws IOException {
            String line = null;
            ArrayList tokens = new ArrayList();
            final String RE = ".*?,.*?,.*?,.*?,.*?,.*?,.*?,.*?,(.*?),.+";
            Pattern pat = Pattern.compile(RE);
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            while ((line = in.readLine()) != null) {
                  Matcher mat = pat.matcher(line);
                  if (mat.matches()) {
                        tokens.add(mat.group(1).trim());
                  }
            }
            in.close();
            return tokens;
      }

      public static void main(String[] args) {
            if (args.length > 0) {
                  ReadNinth rn = new ReadNinth();
                  try {
                        List tokens = rn.collectTokens(args[0]);
                        System.out.println(tokens);
                  }
                  catch (IOException e) {
                        e.printStackTrace();
                  }
            }
            else {
                  printUsage();
            }
      }
      
      private static void printUsage() {
            System.out.println("Usage: java ReadNinth <csv file>");
      }      
}

Too bad it has to be Java. This is making me cry . . .

In Perl:

perl -ne '@arr = split /,/; print "$arr[9]\n"' <cvs.txt
59
0
65
0
85
0

LOL. Give or take a chomp maybe ;-)
You can use split in Java too actually:

tokens.add(line.split(",")[8].trim());

but i'm not advocating that kind of unreadable code compression
ok problem solved... here is my new code... it works by the way. i am still trying to do another thing though so please reply

import java.io.*;          //import necessary libraries for things like tokenizer
import java.util.*;

public class reader
{

  public static void main(String args[])
  {

  //declare global variables
    int totalmarks = 0;
    int numloops = 0;
    String arr1;
    String line;
    String year;

    try //file import code
    {
      File inFile = new File(args[0]);  //create object linked to actual file
      FileReader reader = new FileReader(inFile); //create input stream
      BufferedReader buff = new BufferedReader(reader);

      line = buff.readLine(); //read first line
      while (line != null)  //null returned when no more to read
      {
       numloops++;
       line = buff.readLine(); //get next
       year = line;
      //tokenizing code

      StringTokenizer st = new StringTokenizer(year,",");

      String arr[] = new String[st.countTokens()];

      // below is code to tokenize the string called st at the , mark and output to screen

      for (int i = 0; st.hasMoreTokens(); i++)
      {
          st.nextToken();

          if (i == 7)
          {
          arr1 = st.nextToken();
          //totalmarks = arr1 + totalmarks;       problem here
          System.out.println("------------marks value below------------");
          System.out.println(arr1);
          System.out.println("this is value of totalmarks below----------");
          System.out.println(totalmarks);

          EasyIn.pause();
          }
      }
    }}

    catch(IOException e)
    {
      System.out.println("error has occured: "+e);
    }

  }
}


i need to convert the string variable arr into an int valuie so i can add them up each time it loops.... see the line

totalmarks = arr + totalmarks;

it expects and int + int but it is getting a string + int equation... how can i adapt this easily to make the string into an int.. i think parseint() may work or  intvalue() but am not entirely sure how to use them??

ps: i have upped the points available to 50.. if you think this isnt enough please say so

Sean
Should be

totalmarks += Integer.parseInt(arr1);
this works but i am having trouble wiht the loop. why is the hello statement showing up as i dont see it as being in a loop. also i try to make it show the average at the end but it doesnt work. also i am working on making a frequency table out of the results.. can anyone suggest a way of doing this?? i have used a series of if statements in the loop incrementing a counter each time its requirements are met. the if requirement is not right. can some1 please correc tge following code:

if (Integer.parseInt(arr1) >= 0 & Integer.parseInt(arr1) < 10)

any help is appreciated... agani the points available for this question will be upped for the trouble


import java.io.*;          //import necessary libraries for things like tokenizer
import java.util.*;

public class reader
{

  public static void main(String args[])
  {

  //declare global variables
    int totalmarks = 0;
    int numloops = 0;
    int meanav = 0;
    int freq1 = 0;
    int freq = 0;
    String arr1;
    String line;
    String year;

    try //file import code
    {
      File inFile = new File(args[0]);  //create object linked to actual file
      FileReader reader = new FileReader(inFile); //create input stream
      BufferedReader buff = new BufferedReader(reader);

      line = buff.readLine(); //read first line
      while (line != null)  //null returned when no more to read
      {
             numloops++;
             line = buff.readLine(); //get next
             year = line;
            //tokenizing code

            StringTokenizer st = new StringTokenizer(year,",");

            String arr[] = new String[st.countTokens()];

            // below is code to tokenize the string called st at the , mark and output to screen

                  for (int i = 0; st.hasMoreTokens(); i++)
            {
                st.nextToken();

                if (i == 7)
                  {
                           arr1 = st.nextToken();
                         totalmarks += Integer.parseInt(arr1);
                freq = Integer.parseInt(arr1);
                         System.out.print(totalmarks);
                 EasyIn.pause();
                  }

             //      if (Integer.parseInt(arr1) >= 0 & Integer.parseInt(arr1) < 10)
                  //{
                  //      freq1++;
                  //}
             //      elseif (arr1 >=10 & arr1 < 20)
                  //{
                  //      freq2++;
             //      }

        else
          {
          }
        }
      System.out.println("hello");  //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<why can i see this looping over... is thins part of loop?
      EasyIn.pause();
     }

   }

   catch(IOException e)
   {
      System.out.println("error has occured: "+e);
   }

   meanav = totalmarks / numloops;
   System.out.println("Mean Average is: " +meanav);
   EasyIn.pause();

  }

}


thanks Sean
Is your code meant to skip the first line, as that's what's happening?
yes as it is a csv file, it contains the following:

Year,Period,Module,Occ,Map,#Ass#,#Cand Key,Name,#CD,Mark,Grade,CD,#Cand Key
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10001,,#87,59,,,10001
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10002,,#35,0,,,10002
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10003,,#87,65,,,10003
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10004,,#68,0,,,10004

i need the data not the field name

although in the future i am planning to make the program determine where the marks line is so it is more versatile. i am looking for a way to get my frequency table to work.. are if statements the easiest way?? or most efficient

why does the last section not show? i have added an easyin.pause so theoretically it should stop??

please help

Sean
>>why does the last section not show?

Please say what happens when all those pauses are removed
i get something that looks like this:

3974
Hello

4310
Hello  <<this shuouldnt show..it is outside the loop

exception in thread "main" java.lang.nullpointerexception
                at java.util.stringtokenizer.<init><unknown source>
                at java.util.stringtokenizer.<init><unknown source>
                at reader.main<reader.java:64>

does this help??
Change

>>while (line != null)  //null returned when no more to read

to

while ((line = buff.readLine) != null)  //null returned when no more to read

and remove

>>line = buff.readLine(); //get next

thats neatened the code up a bit but hasnt helped the exception. exception still there and avergae bit not showing still

Sean
I've an idea of what's happening but i'd like you to paste the actual exception. The one you posted before has been typed by you
Oh and let me know what version of Java you're using
right i dowenloaded java 5. ic ant give you the exception because you cant copy and paste form a command prompt window

do you need it or shall i type it exaxctly as i see it??
Replace:
           for (int i = 0; st.hasMoreTokens(); i++)
           {
               st.nextToken();

               if (i == 7)
               {
                        arr1 = st.nextToken();
                       totalmarks += Integer.parseInt(arr1);
                       freq = Integer.parseInt(arr1);

By:
           for (int i = 0; st.hasMoreTokens(); i++)
           {
               String s = st.nextToken();

               if (i == 7)
               {
                       totalmarks += ( freq = Integer.parseInt( arr1 = s ) );
now its saying that readLine is not found in class java.io.BufferedReader

it highlights this line:

   while ((line = buff.readLine) != null)

any sugestions?
>>you cant copy and paste form a command prompt window


You can actually. You'll find the following works ok:


public class reader {

      public static void main(String args[]) {

            //declare global variables
            int totalmarks = 0;
            int numloops = 0;
            int meanav = 0;
            int freq1 = 0;
            int freq = 0;
            String arr1;
            String line;
    Histogram histogram = null;
            try {
                  //file import code

                  histogram = new Histogram();
                  File inFile = new File(args[0]);
                  //create object linked to actual file
                  FileReader reader = new FileReader(inFile);
                  //create input stream
                  BufferedReader buff = new BufferedReader(reader);

                  line = buff.readLine();
                  //read first line
                  while ((line = buff.readLine()) != null) {
                        //null returned when no more to read

                        numloops++;
                        String[] tokens = line.split(",");

                        try {
                              int score = Integer.parseInt(tokens[9]);
                              histogram.addFrequency(score);
                              totalmarks += score;
                        }
                        catch (NumberFormatException e) {
                              // Don't know what to do;
                        }

                        //get next
                        //tokenizing code

                  }
                  // end while

            }

            catch (IOException e) {
                  System.out.println("error has occured: " + e);
            }

            meanav = totalmarks / numloops;
            System.out.println("Mean Average is: " + meanav);
            System.out.println(histogram);

      }
}

class Histogram {


      private int[] frequencyTable;


      public Histogram() {
            frequencyTable = new int[11];
      }


      public void addFrequency(int datum) {
            // Bounds check
            if (datum >= 0 && datum <= 100) {
                  frequencyTable[(int) (datum / 10)]++;
            }
      }


      public String toString() {
            StringBuffer result = new StringBuffer();
            
            for (int i = 0; i < frequencyTable.length; i++) {
                  //result.append(frequencyTable[i]).append(",");
                  int upperLimit = lowerLimit + 9;
                  result.append(lowerLimit).append("-").append(upperLimit).append(": ").append(frequencyTable[i]).append("\n");
            }
            //return result.toString().substring(0, result.length() - 1);
            return result.toString().trim();
      }

      // Add method to display the table
}
Replace:
  while ((line = buff.readLine) != null)
By:
  while ((line = buff.readLine()) != null)
CHEJ the code u posted threw up a loada errors.i imported the libraries and it only had 3 errors remaining

error (33) method split[java.lang.string] not found in class java.lang.string
error (87) variable lower limit not found in class histogram
error (88) variable lower limit not found in class histogram

webstorm thanks your last comment worked and it now compiles but the following error appears when in a command window

any ideas?

C:\Documents and Settings\Sean\Desktop\Work>java reader
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at reader.main(reader.java:52)

C:\Documents and Settings\Sean\Desktop\Work>java reader marks.csv
Exception in thread "main" java.lang.NumberFormatException: For input string: "#
87"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at reader.main(reader.java:76)

i managed to copy and paste all of this lot. i hope you can help.

CHEJ if you can find out why your version isnt working i will be happy to use it and end this asap.

ps:      // Add method to display the table ------------------how?? thats another thing i cant do.. i can only make it output standard text to screen

Sean
>>error (33) method split[java.lang.string] not found in class java.lang.string

Means you've got an old version of java (i.e. below 1.4) which means you'll be missing out on a lot of functionality in the standard libraries. I'll have a look at the other errors
For the other errors, just use the following toString:

      public String toString() {
            StringBuffer result = new StringBuffer();
            
            for (int i = 0; i < frequencyTable.length; i++) {
                  int lowerLimit = i * 10;
                  int upperLimit = lowerLimit + 9;
                  result.append(lowerLimit).append("-").append(upperLimit).append(": ").append(frequencyTable[i]).append("\n");
            }
            return result.toString().trim();
      }

when i try and config java 1.5 i get

error (0) initialization error: com.borland.compiler.symtab.loaderror: class file has wrong version 49.0.

this isnt good is it... can u suggest a place where  can get a compiler thats works properly because mine isnt workng properly

Sean

ps: if not please can u see if there is a java 1.2 happy version of split?
ok errors sorted just the split error to go

 and can u help me write amethod to display all of my results?? would be  very much appreciated

Sean
>>ok errors sorted just the split error to go

That will disappear when you get yourself a proper up-to-date copy of Java (although i wouldn't go for 1.5 quite yet)

Already done

>>
and can u help me write amethod to display all of my results?? would be  very much appreciated
>>

ok do you know of a good FREE ide i can use

i downloaded 1.5 but it came with 1.4 too so i can import that when i get a good compiler

help

Sean
I personally wouldn't use an IDE until you're more experienced or you won't learn Java properly from first principles. All you need is a good editor.
ok please can u suggest to me a good editor

Sean

If you use Ultraedit, you can configure buttons to compile and run your java files.
For the 2 exceptions :

>> C:\Documents and Settings\Sean\Desktop\Work>java reader
>> Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
>>         at reader.main(reader.java:52)
You forgot to specify the file argument, you can test if the 1st argument exists :
    if (args.length<=0) // no arguments
    {
        System.out.println("syntax:  filename");
        System.exit(0);
    }

>> C:\Documents and Settings\Sean\Desktop\Work>java reader marks.csv
>> Exception in thread "main" java.lang.NumberFormatException: For input string: "#87"
You need to skip this token, Replace :
    if (i == 7)
By:
    if (i == 8)

Vis-a-vis the output, this is what the program produces with a test file of four lines

Mean Average is: 56
0-9: 1
10-19: 0
20-29: 0
30-39: 0
40-49: 0
50-59: 1
60-69: 1
70-79: 0
80-89: 0
90-99: 0
100-109: 1
webstorm how exactly can i compile and run my java fles?? i got it to open the file but not compile or run... where do i need to click

Sean
I don't know Ultraedit but even there i would not use the gui facility for compiling and running - you'll learn more if you use the command line - at least to begin with
ok so explain to me please how i can compile and run easily from the command line

ps: do you ever sleep
Sean
LOL - i should be going to sleep by now.

compile:

javac YourClass.java

run

java YourClass

Make sure <java installation path>\bin

is on your path

cheers i will l try that

i will sort points wen i get it all up and running..i will do a 66% u and 34% webstorm split unless u think that isnt fair
Seems OK

If you want to compile & run with Ultraedit, you must add a new tool :

1 - Menu  Advanced / Tool Configuration ...
2 - In "Command Line", you can type:
         <jdkpath>\bin\javac.exe -classpath "<other_path>;%p;." "%n"
     where <jdkpath> is the path of your JDK installation, and <other_path> is the list of directories and jar fiels you want in your classpath.
     %p will be replaced by the path of your current file
     %n will be replaced by the name of your current file
3 - "Working directory" :
         %p
4 - "Menuitem" :
          Java compilation
5 - click the "Insert" button, and "OK"

Now you can select "User Tool 1" in the "Advanced" menu to compile your java file, or you can add a button to the toolbar :
6 - Right click on toolbar, select "Customize..."
7 - Drag & drop the "User Tool 1" command to the toolbar to insert the new button.
8 - click "OK"

im working on comments for the code.... now can you please explain to me exactly what these commands do (i know they are part of method but i am commenting each line.

1.  result.append(lowerLimit).append("-").append(upperLimit).append(": ").append(frequencyTable[i]).append("\n");
2.  return result.toString().trim();
3. frequencyTable[(int) (datum / 10)]++;
4. Histogram histogram = null;

Sean
1. Formats the String for the output of the frequency table
2. Return String to print trimmed of whitespace
3. Increment the frequency for the appropriate score
4. Initialize the Histogram
3. frequencyTable[(int) (datum / 10)]++;

this line confuses me..i understand your comment but i am really havbing trouble understanding what actually goes on

from what i can see the variable frequencytable is incremented by one but the square bracket eludes me completely.

what exectly does[(int) (datum / 10)] do... is it a sort of guard? does the value only increment when the requirements are met

the int bit..is it a variable and why are you dividing datum by 10

just trying to get my head round it

Sean
 frequencyTable[  (int) (datum / 10)  ]++;

  frequencyTable is an array
  (int) (datum / 10)    is the frequency index in the array
  ++  add one to the   (int) (datum / 10)  th element of the array

datum is alreay an int, the conversion is not needed :

frequencyTable[  datum/10  ]++;

In the code posted by CEHJ, datum is divided by 10 in order to count the frequency for datum 0-9 ( 0/10 == 0 == 9/10 ), 10-19 ( 10/10 == 19/10 == 1 ), ...

Is that clear now Sean? Think of it being the logical equivalent of find the correct column in a histogram and drawing it a unit higher after finding a mark that fits in that column
ok i get it..you are deciding what space in the array you want o increment and add 1 to it

thanks

still having sompilation troubles
Yes

>>still having sompilation troubles

Are you using the code i gave you?
yes but compiler problems etc..
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cd program files

C:\Program Files>cd java

C:\Program Files\Java>cd bin
The system cannot find the path specified.

C:\Program Files\Java>dir
 Volume in drive C has no label.
 Volume Serial Number is 68F8-142A

 Directory of C:\Program Files\Java

04/14/2004  04:39 PM    <DIR>          .
04/14/2004  04:39 PM    <DIR>          ..
04/02/2004  01:54 PM    <DIR>          j2re1.4.1_02
04/14/2004  04:39 PM    <DIR>          j2re1.5.0
04/14/2004  04:39 PM    <DIR>          j2sdk1.5.0
               0 File(s)              0 bytes
               5 Dir(s)  71,637,057,536 bytes free

C:\Program Files\Java>cd j2sdk1.5.0

C:\Program Files\Java\j2sdk1.5.0>cd bin

C:\Program Files\Java\j2sdk1.5.0\bin>javac reader2
javac: invalid flag: reader2
Usage: javac <options> <source files>
where possible options include:
  -g                         Generate all debugging info
  -g:none                    Generate no debugging info
  -g:{lines,vars,source}     Generate only some debugging info
  -nowarn                    Generate no warnings
  -verbose                   Output messages about what the compiler is doing
  -deprecation               Output source locations where deprecated APIs are u
sed
  -classpath <path>          Specify where to find user class files
  -cp <path>                 Specify where to find user class files
  -sourcepath <path>         Specify where to find input source files
  -bootclasspath <path>      Override location of bootstrap class files
  -extdirs <dirs>            Override location of installed extensions
  -endorseddirs <dirs>       Override location of endorsed standards path
  -d <directory>             Specify where to place generated class files
  -encoding <encoding>       Specify character encoding used by source files
  -source <release>          Provide source compatibility with specified release

  -target <release>          Generate class files for specific VM version
  -version                   Version information
  -help                      Print a synopsis of standard options
  -X                         Print a synopsis of nonstandard options
  -J<flag>                   Pass <flag> directly to the runtime system


C:\Program Files\Java\j2sdk1.5.0\bin>javac reader2.java

C:\Program Files\Java\j2sdk1.5.0\bin>java reader2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at reader2.main(reader2.java:64)

C:\Program Files\Java\j2sdk1.5.0\bin>java reader2.java
Exception in thread "main" java.lang.NoClassDefFoundError: reader2/java

C:\Program Files\Java\j2sdk1.5.0\bin>java reader2.java marks.csv
Exception in thread "main" java.lang.NoClassDefFoundError: reader2/java

C:\Program Files\Java\j2sdk1.5.0\bin>java reader2 marks.csv
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
        at reader2.main(reader2.java:76)

compiled fine but got these errors (used command line compiler like you said

Sean
The code at
https://www.experts-exchange.com/questions/20953776/help-need-quick-answer.html#10858482

will compile as is. You just need the correct imports
You shouldn't be putting class files in the bin directory

java reader2 marks.csv

Is the one you need. I *was* going to suggest removing the literal from the code. Now is a good time.


private static int MARKS_COLUMN = 9; // (AT THE TOP OF THE CODE - above main) The number of the marks column goes in here

Then replace

>>int score = Integer.parseInt(tokens[9]);

by

int score = Integer.parseInt(tokens[MARKS_COLUMN]);


right i have compiled it in java using the command line with no problems. now i try and run it and i get :

C:\Program Files\Java\j2sdk1.5.0\bin>javac reader2.java

C:\Program Files\Java\j2sdk1.5.0\bin>java reader2 marks.csv
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
        at reader2.main(reader2.java:76)

i cant get rid of this

Sean
btw what is the point of this:

private static int MARKS_COLUMN = 9;

why are you using it? does it make the program mor efficient?

Sean
That means that there are fewer than 9 columns in the source file. Are you sure you understand what the program is meant to be doing?
>>does it make the program mor efficient?

No but it makes it more maintainable
i am trying to understand it... ther are not though. you handed ,me the code how can it be not working

are you sure that 9 is the right number? i changed it to 8 and it came up with a load or errors.

here is the entire marks.csv file

Year,Period,Module,Occ,Map,#Ass#,#Cand Key,Name,#CD,Mark,Grade,CD,#Cand Key
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10001,,#87,59,,,10001
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10002,,#35,0,,,10002
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10003,,#87,65,,,10003
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10004,,#68,0,,,10004
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10005,,#51,85,,,10005
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10006,,#94,0,,,10006
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10007,,#67,0,,,10007
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10008,,#26,2,,,10008
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10009,,#20,40,,,10009
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10010,,#00,70,,,10010
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10011,,#94,50,,,10011
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10012,,#28,27,,,10012
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10013,,#13,80,,,10013
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10014,,#48,52,,,10014
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10015,,#15,0,,,10015
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10016,,#75,38,,,10016
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10017,,#81,0,,,10017
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10018,,#58,8,,,10018
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10019,,#17,65,,,10019
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10020,,#89,23,,,10020
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10021,,#26,0,,,10021
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10022,,#23,55,,,10022
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10023,,#99,65,,,10023
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10024,,#46,62,,,10024
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10025,,#24,62,,,10025
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10026,,#23,52,,,10026
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10027,,#04,40,,,10027
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10028,,#51,90,,,10028
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10029,,#52,70,,,10029
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10030,,#04,0,,,10030
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10031,,#95,7,,,10031
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10032,,#92,0,,,10032
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10033,,#00,0,,,10033
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10034,,#89,61,,,10034
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10035,,#61,85,,,10035
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10036,,#68,0,,,10036
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10037,,#37,78,,,10037
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10038,,#91,0,,,10038
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10039,,#70,57,,,10039
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10040,,#93,70,,,10040
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10041,,#02,55,,,10041
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10042,,#87,36,,,10042
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10043,,#69,75,,,10043
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10044,,#93,0,,,10044
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10045,,#95,0,,,10045
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10046,,#93,55,,,10046
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10047,,#29,42,,,10047
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10048,,#95,63,,,10048
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10049,,#55,37,,,10049
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10050,,#29,0,,,10050
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10051,,#55,50,,,10051
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10052,,#90,61,,,10052
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10053,,#71,41,,,10053
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10054,,#64,90,,,10054
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10055,,#99,56,,,10055
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10056,,#00,77,,,10056
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10057,,#04,58,,,10057
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10058,,#33,63,,,10058
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10059,,#99,38,,,10059
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10060,,#51,35,,,10060
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10061,,#25,58,,,10061
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10062,,#75,0,,,10062
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10063,,#43,68,,,10063
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10064,,#04,65,,,10064
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10065,,#24,0,,,10065
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10066,,#46,0,,,10066
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10067,,#54,67,,,10067
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10068,,#88,0,,,10068
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10069,,#34,63,,,10069
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10070,,#58,63,,,10070
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10071,,#90,50,,,10071
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10072,,#57,40,,,10072
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10073,,#08,0,,,10073
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10074,,#13,58,,,10074
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10075,,#74,80,,,10075
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10076,,#77,0,,,10076
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10077,,#96,68,,,10077
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10078,,#13,25,,,10078
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10079,,#27,68,,,10079
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10080,,#57,70,,,10080
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10081,,#79,0,,,10081
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10082,,#04,49,,,10082
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10083,,#68,63,,,10083
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10084,,#19,70,,,10084
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10085,,#60,65,,,10085
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10086,,#56,0,,,10086
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10087,,#07,0,,,10087
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10088,,#88,57,,,10088
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10089,,#52,67,,,10089
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10090,,#90,85,,,10090
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10091,,#08,72,,,10091
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10092,,#93,23,,,10092
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10093,,#34,0,,,10093
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10094,,#19,0,,,10094
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10095,,#25,0,,,10095
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10096,,#82,57,,,10096
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10097,,#88,73,,,10097
2003/4,SEM1,CSD1005C,C99,CSD1005C,#010,10098,,#48,72,,,10098

please see if using this you can get the program working... something is stoipping it form working here.

i have done exctly as you said and im not getting anywhere. as you can see in the file, the 9th column is the one i want.

Sean
This is the output i get with that file:

Mean Average is: 41
0-9: 30
10-19: 0
20-29: 4
30-39: 5
40-49: 6
50-59: 16
60-69: 19
70-79: 11
80-89: 5
90-99: 2
100-109: 0
ok where are you storing your files, all of my files classes and .java are stored in  c:\<<java dir>>\bin\

and i have also put marks.csv in there as well

i dont see why it isnt working

Sean
This part of the program is correct isn't it?

                  File inFile = new File(args[0]);
yes... if not it wouoldnt compile??

i have tried changing the value in front of marks_column and it is definately importing the filoe because of the errors i encounter.

let me redownload java from the web but 1.4 this time and i will try again in the morning. then hopefully the bugger will work

thanks for your help. if it works points will be sorted then

Sean
It's easier if i just post the whole thing again and you copy and paste it. Coming in next post
import java.io.*;

public class reader {
  private static int MARKS_COLUMN = 9;


  public static void main(String args[]) {

    //declare global variables
    int totalmarks = 0;
    int numloops = 0;
    int meanav = 0;
    String line;
    Histogram histogram = null;
    try {
      //file import code

      histogram = new Histogram();
      File inFile = new File(args[0]);
      //create object linked to actual file
      FileReader reader = new FileReader(inFile);
      //create input stream
      BufferedReader buff = new BufferedReader(reader);

      line = buff.readLine();
      //read first line
      while ((line = buff.readLine()) != null) {
        //null returned when no more to read

        numloops++;
        String[] tokens = line.split(",");

        try {
          int score = Integer.parseInt(tokens[MARKS_COLUMN]);
          histogram.addFrequency(score);
          totalmarks += score;
        }
        catch (NumberFormatException e) {
          // Don't know what to do;
        }

        //get next
        //tokenizing code

      }
      // end while

    }

    catch (IOException e) {
      System.out.println("error has occured: " + e);
    }

    meanav = totalmarks / numloops;
    System.out.println("Mean Average is: " + meanav);
    System.out.println(histogram);

  }
}

class Histogram {


  private int[] frequencyTable;


  public Histogram() {
    frequencyTable = new int[11];
  }


  public void addFrequency(int datum) {
    // Bounds check
    if (datum >= 0 && datum <= 100) {
      frequencyTable[datum / 10]++;
    }
  }


  public String toString() {
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < frequencyTable.length; i++) {
      int lowerLimit = i * 10;
                  int upperLimit = lowerLimit + 9;
      result.append(lowerLimit).append("-").append(upperLimit).append(": ").append(frequencyTable[i]).append("\n");
    }
    return result.toString().trim();
  }

}

This is what i get now

i have just downloaded the j2sdk1.4.2_04 which now lies at c:\...

i have copied reader and reader2 and marks.csv into the bin directory of the sdk.

the following is the full version of my command window. is it my pc thats not working??


Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cd program files

C:\Program Files>cd java

C:\Program Files\Java>cd j2sdk1.5.0

C:\Program Files\Java\j2sdk1.5.0>javac reader.java
'javac' is not recognized as an internal or external command,
operable program or batch file.

C:\Program Files\Java\j2sdk1.5.0>cd bin

C:\Program Files\Java\j2sdk1.5.0\bin>javac reader.java

C:\Program Files\Java\j2sdk1.5.0\bin>java reader marks.csv
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
        at reader.main(reader.java:34)

C:\Program Files\Java\j2sdk1.5.0\bin>cd..

C:\Program Files\Java\j2sdk1.5.0>cd..

C:\Program Files\Java>cd..

C:\Program Files>cd..

C:\>cd j2sdk1.4.0_02
The system cannot find the path specified.

C:\>dir
 Volume in drive C has no label.
 Volume Serial Number is 68F8-142A

 Directory of C:\

03/17/2004  02:24 AM                 0 AUTOEXEC.BAT
03/17/2004  02:24 AM                 0 CONFIG.SYS
03/17/2004  02:28 AM    <DIR>          Documents and Settings
04/21/2004  01:10 AM    <DIR>          j2sdk1.4.2_04
04/19/2004  07:18 PM    <DIR>          Program Files
04/06/2004  02:43 PM    <DIR>          Valve
04/19/2004  07:19 PM    <DIR>          WINDOWS
03/17/2004  04:12 PM    <DIR>          WUTemp
               2 File(s)              0 bytes
               6 Dir(s)  71,237,521,408 bytes free

C:\>cd j2sdk1.4.2_04

C:\j2sdk1.4.2_04>cd bin

C:\j2sdk1.4.2_04\bin>javac reader2.java

C:\j2sdk1.4.2_04\bin>java reader2 marks.csv
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
        at reader2.main(reader2.java:79)

C:\j2sdk1.4.2_04\bin>javac reader marks.csv
javac: invalid flag: reader
Usage: javac <options> <source files>
where possible options include:
  -g                        Generate all debugging info
  -g:none                   Generate no debugging info
  -g:{lines,vars,source}    Generate only some debugging info
  -nowarn                   Generate no warnings
  -verbose                  Output messages about what the compiler is doing
  -deprecation              Output source locations where deprecated APIs are us
ed
  -classpath <path>         Specify where to find user class files
  -sourcepath <path>        Specify where to find input source files
  -bootclasspath <path>     Override location of bootstrap class files
  -extdirs <dirs>           Override location of installed extensions
  -d <directory>            Specify where to place generated class files
  -encoding <encoding>      Specify character encoding used by source files
  -source <release>         Provide source compatibility with specified release
  -target <release>         Generate class files for specific VM version
  -help                     Print a synopsis of standard options


C:\j2sdk1.4.2_04\bin>javac reader.java

C:\j2sdk1.4.2_04\bin>java reader marks.csv
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
        at reader.main(reader.java:34)

C:\j2sdk1.4.2_04\bin>


Sean
Replace :
  String[] tokens = line.split(",");
By :
  String[] tokens = line.split(",", MARKS_COLUMN);


You can also test if the MARKS_COLUMN th columns exists :

  if (tokens.length<=MARKS_COLUMN) // tokens[MARKS_COLUMN] doesn't exists
       System.err.println("Les then "+MARKS_COLUMN+" columns in ("+line+")");
  else
  try{
    ...
C:\j2sdk1.4.2_04\bin>javac reader2.java

C:\j2sdk1.4.2_04\bin>java reader2 marks.csv
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
        at reader2.main(reader2.java:79)

C:\j2sdk1.4.2_04\bin>java reader2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at reader2.main(reader2.java:67)


made all modifications suggested and the above response is returned.

Sean
>>        at reader2.main(reader2.java:79)
What is the 79th line in your java file ?

numloops++;

i dont see why this could be wrong... does it mean actual lines or lines with code on?

import java.io.*;               //import necessary libraries
import java.util.*;

public class reader2      //start of reader2.class
{
      
     private static int MARKS_COLUMN = 9;
     
     public static void main(String args[])      //start of main function
     {

                                  //declare global variables
          int totalmarks = 0;
          int numloops = 0;
          int meanav = 0;
          int freq1 = 0;
          int freq = 0;
          int score = 0;
          String arr1;
          String line;      //used for storing the imported file a line at a time
          Histogram histogram = null;      //Initialize the Histogram

      if (tokens.length<=MARKS_COLUMN) // tokens[MARKS_COLUMN] doesn't exists
        {
              System.err.println("Les then "+MARKS_COLUMN+" columns in ("+line+")");
        }
        else
        {
          try       //start first try/catch
          {

               histogram = new Histogram();        //creates a new histogram object
               File inFile = new File(args[0]);     //tells the program to accept a filename that is imput as a command line argument
               FileReader reader = new FileReader(inFile); //create object linked to actual file
               BufferedReader buff = new BufferedReader(reader); //create input stream

               line = buff.readLine();                            //reads first line of code (gets rid of titles)
               while ((line = buff.readLine()) != null)         //while there is more of the imported file to be read, carry on looping
               {
                    numloops++;         //used for mean average (total number of loops = total number of numbers)
                    String[] tokens = line.split(",", MARKS_COLUMN);  //investigated string tokenizer but split seemed easier to use

                    try //start second try/catch
                    {
                        score = Integer.parseInt(tokens[9]);  //parseint converts a string to an integer and stores the result in a variable called score
                        histogram.addFrequency(score);     //calls the method add frquency formt he class histogram
                        totalmarks += score;            //running total of all values entered
                    }      //end try
                    catch (NumberFormatException e)
                    {
                          System.out.println("error has occured: " + e);  //saves an exception to the varable e (if there is one)
                    }    //end second try/catch

               }   // end while loop

          }      //end try

          catch (IOException e)            //saves an exception to the varable e (if there is one)
          {
               System.out.println("error has occured: " + e); //outputs "error has occured" and Exception details
          }      //end of first try/catch
      }
          meanav = totalmarks / numloops;      //calculates mean average
          System.out.println("Mean Average is: " + meanav);      //outputs mean average
          System.out.println(histogram);      //outputs the histogram to the screen

     }      //end of main function
}      //end if reader2.class

class Histogram      //start of histogram.class
{

     private int[] frequencyTable;      //declares an array that can only be used by this class


     public Histogram()      //method histogram
     {
          frequencyTable = new int[11]; //initialises new Array with 11 spaces
     }                  //end  of method histogram


     public void addFrequency(int datum)      //add frequency method
     {
         
          if (datum >= 0 && datum <= 100)      // Bounds check
          {
               frequencyTable[(int) (datum / 10)]++;      //Increment the frequency for the appropriate score
          }
     }                        //end of method addfrequency


     public String toString()
     {
          StringBuffer result = new StringBuffer();      //assigns the name result to a new string buffer and initialises it
         
          for (int i = 0; i < frequencyTable.length; i++)
          {
               int lowerLimit = i * 10;      //configures lower limits of histogram
               int upperLimit = lowerLimit + 9;      //configures upper limits of histogram
               result.append(lowerLimit).append("-").append(upperLimit).append(": ").append(frequencyTable[i]).append("\n");
               //Formats the String for the output of the frequency table
               
          }
          return result.toString().trim();      //Return String to print trimmed of whitespace
     }
}      //end of histogram class

this might help

Sean
Replace:
                    String[] tokens = line.split(",", MARKS_COLUMN);  //investigated string tokenizer but split seemed easier to use

                    try //start second try/catch
                    {
By:
                    String[] tokens = line.split(",", MARKS_COLUMN);  //investigated string tokenizer but split seemed easier to use
                    if (tokens.length<=MARKS_COLUMN) // tokens[MARKS_COLUMN] doesn't exists
                         System.err.println("Less than "+MARKS_COLUMN+" columns in ("+line+")");
                   else
                    try //start second try/catch
                    {
If you get "Less than 9 columns in()", you should manage empty lines:


                if (line.trim().length()==0) continue; // skip empty lines

                String[] tokens = line.split(",", MARKS_COLUMN);  
                ...
Sean - you're not doing anyone any favours here:

a. I've given you working code
If you want to change it, do so in such a way that doesn't break it, i.e. carefully and incrementally.

b. If you have problems post the code you are using. It's no good pointing out runtime errors and then posting code that won't even compile
this code i have posted above is the same as what you have posted only it has comments in it. i am making modifications as i go when you or webstorm suggest them. what else can i do. from what i can see it compiles ok but i am getting errors. trust me its annoying me as much as it is you

webstorm where do i put the if statement and does the end of the infile not count as an empty line??

Sean
>>this code i have posted above is the same as what you have posted only it has comments in it

It isn't the same. Yours has this in it for one thing:

>>if (tokens.length

etc. 'tokens' has not been declared, therefore this code cannot possibly compile, so it can't possibly be the same code for which you reported runtime errors

ok then, i copied and pasted the last code you posted and got thesame exception. array index out of bounds line 34

Sean
SOLUTION
Avatar of Webstorm
Webstorm

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK. Now we're talking. I'll use that and try it *with the values file you posted*
thankyou for your help...

Sean
The result of running this code:

http:#10873437

with this input file

http:#10873296

is the following


Mean Average is: 41
0-9: 30
10-19: 0
20-29: 4
30-39: 5
40-49: 6
50-59: 16
60-69: 19
70-79: 11
80-89: 5
90-99: 2
100-109: 0

So if you're getting something else, the most likely explanation is you're using different code
then it must be where its all working. i have moved marks.csv and the reader.java file to  the bin directory

the directory is c:\j2sdk1.4.2_04\bin\

i compile by typing javac reader3.java (i changed the name)

i run by typing java reader3 marks.csv

do i need to change where the classes are stored because currently they are stored in the bin folder with the rest.

this i sgetting annoying. i can see how hard it is for you too though.

Sean
>>this i sgetting annoying

Just take it incrementally and recompile/retest after every change or you'll get into a mess.

>>do i need to change where the classes are stored because currently they are stored in the bin folder with the rest.

As i mentioned before, there should be none of your code or files in there anyway. Since there are no explicit packages being used here, just put everything in one directory
ok ive moved it all to another directory called c:\test

i have recompiled and am still getting the exception but on line 34 this time. line 34 reads:

int score = Integer.parseInt(tokens[MARKS_COLUMN);

i have tried to change it back to 9 but it makes no difference

Sean
Please paste the actual exception stack trace.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
           at reader3.main<reader3.java:34>


Sean
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i copied and pasted form the code you listed. renamed it to reader3 in the class mae in the file and in the filename. then saved it as a .java then copied to c:\test

ok i dont want to bother you any further. its obviously a problem on my end. thankyou for all of your help. i have upped the points to 75 and you will get 50.

Sean
i need to add a new message to up the points

lol

Sean
Actually i meant the csv file not the java one (although of course the latter could also be the case)

Make *another* file like this:

X,X,X,X,X,X,X,X,X,X,X
0,0,0,0,0,0,0,0,0,0,z
0,0,0,0,0,0,0,0,0,1,z
0,0,0,0,0,0,0,0,0,2,z

and try it
now were getting somewhere. it works with your exacmple. now if your still willing to help. how can i make it work with marks.csv??

Sean
Make sure marks.csv is not wrong, which it almost certainly is ;-)
yep you were right. the marks.csv file was wrong somehow. i copied and pasted it into a file called marks2.cav and it worked perfectly...thanks to you all for your help

Sean
Phew ;-)