Results 1 to 5 of 5
  1. #1
    Xeher is offline Member
    Join Date
    Nov 2010
    Posts
    3
    Rep Power
    0

    Default Urgent! Java Assignment with loops in Arrays

    Good evening,
    I am relatively new to Java, and Arrays and using loops in arrays is proving a little trivial for me. I have the following assignment (most of which is done), I really need help in solving a certain chunk of code:

    The purpose of this assignment is to familiarize you with arrays and lops in Java. In this
    assignment you will have to implement a program that calculates and visualizes the character
    count for all letters in a text file. Your program will have to do the following:
    - Read the file into an array of chars. The program skeleton provided already does this.
    - Go through every character in the array and calculate the number of occurrences of every letter
    (you can assume that the text is written using the 26-letter English alphabet). All other
    characters must be ignored. Upper- and lower-case forms of the same letter must be treated
    the same - e.g. 'A' counts as an occurrence of 'a'. You must use an array of 26 ints to store the
    counts, i.e., don't use separate variables like countA, countB, countC, etc.
    - Once you have processed the entire array, display the histogram of character counts in one of
    the two ways:
    1. Count histogram, where the length of each bar - i.e. the number of characters in it - is the
    calculated count for that character. For example, if there were 10 a's, 8 b's, and 13 c's, the
    first three lines of your program's output should look like this:
    aaaaaaaaaa
    bbbbbbbb
    ccccccccccccc
    ...
    2. Normalized histogram. A text screen is typically only 80 characters wide, but many text files
    will have histogram bars more than 80 characters long, resulting in rather ugly output. To
    avoid this, you will have to normalize the length of the histogram bars, so that the longest bar
    is no more than, say, 40 characters long. You can do this using the following algorithm:
    1. Find the letter with the largest count maxCount
    2. If maxCount > 40, calculate the scaling factor as 40 / maxCount
    3. To compute the normalized counts, multiply the count for every letter by this scaling
    factor
    4. Display the histogram using the normalized counts

    Implementation
    Two sample text files are provided: wonderland.txt (the full text for "Alice in Wonderland") and looking_glass.txt ("Through the Looking Glass"). Use these files to test the program.
    The files are passed as command line arguments, e.g.:
    java Assign2 wonderland.txt
    You should probably create some other smaller text files to test your program's correctness. Also, read up on the char type in Java and how characters are represented (textbook/lecture/Teh Interwebz). Characters have integer codes and they are sequential. In other words, the code for 'b' is the code for 'a'+1; the code for 'z' is the code for 'a'+25. Use this idea and you will avoid writing a switch statement with 26 cases...

    Attached are the two text files mentioned.

    This is the code I have worked on so far, and the commented area shows where I need help
    Java Code:
    import java.io.*;
    
    public class Assign2
    {
      public static void main(String[] args)
      {
        char[] textArr;
        int maxC = 0;
        double scaleF;
        int[] counts = new int[26];
        
        if (args.length != 1)
        {
          System.out.println("Invalid number of arguments");
          System.out.printf("Usage: Assign2 file_name\n");
          System.exit(1);
        }
        
        //If readFile cannot open the file, it exits the program
        textArr = readFile(args[0]);
        //
        //
        //A bunch of for loops go here, with one nested for loop I am sure.
        //Don't know what else to do. NEED HELP!!
        //
        //
      }
      
      public static char[] readFile(String fileName)
      {
        final int MAX_FILE = 1000000;
        char[] tmpArr = new char[MAX_FILE];
        char[] textArr = new char[1];
        
        try 
        {
          BufferedReader in = new BufferedReader(new FileReader(fileName));
          int tmp;
          int i = 0;
          while ( (tmp = in.read()) != -1 ) 
          {
            tmpArr[i++] = (char)tmp;
          }
          
          textArr = new char[i];
          System.arraycopy(tmpArr, 0, textArr, 0, i);
          System.out.printf("read %d chars\n", i);
          
        } 
        catch (Exception e) 
        {
          System.out.println("Failed to open "+fileName+". Does the file exists?");
          System.out.println("Exiting...");
          System.exit(1);
        }
        return textArr;
      }
    }
    Through the Looking Glass:
    Java Code:
    http://www.4shared.com/document/iVO6qTXn/looking_glass.html
    Alice in Wonderland:
    Java Code:
    http://www.4shared.com/document/vUwfUyuf/wonder.html

  2. #2
    Xeher is offline Member
    Join Date
    Nov 2010
    Posts
    3
    Rep Power
    0

    Default

    P.s: The 4shared files are uploaded from my own account, so no worries :)

  3. #3
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    OK, so you have the program usage sorted out.

    Go through every character in the array and calculate the number of occurrences of every letter (you can assume that the text is written using the 26-letter English alphabet). All other characters must be ignored. Upper- and lower-case forms of the same letter must be treated the same - e.g. 'A' counts as an occurrence of 'a'. You must use an array of 26 ints to store the counts

    So on with the next bit.

    Begin by creating the int array to hold the counts. Then use a for loop to work along the char array updating the count array elements.

    This is best done in a separate method to which to pass the char array and which returns the int (count) array.

    ----------

    the code for 'b' is the code for 'a'+1; the code for 'z' is the code for 'a'+25
    Using this fact you should be able to work out an if condition that tells whether a character is one for which the count array should be updated. The CHaracter method toLowerCase() may help with this.

    Also a hint which may or may not be useful: Think about the expression countArr[ch - 'a'] where ch is a char variable. If ch had a particular value like 'c', which array element would countArr[ch - 'a'] be?

  4. #4
    Xeher is offline Member
    Join Date
    Nov 2010
    Posts
    3
    Rep Power
    0

    Default

    thanks, but instead of using nested for loops in order to fill the array with characters from a to z, i used a bunch of if and else if statements, and then used a for loop to keep track of the occurrences of the letters in the entire text, limiting it to the array length itself for the Histogram. So it was something like this:

    // Histogram Display

    for(int counting = 0; counting < counts.length; counting++)
    {
    display=counts[counting]/scale;

    if (display == 0)
    System.out.printf("%c", letterArray[counting]);

    for(int letter=0;letter<display;letter++)
    {
    System.out.printf("%c", letterArray[counting]);
    }

    System.out.printf("\n");
    }
    }
    It is giving the correct result, but I hope my instructor does not penalize me for the 26 if statements i used to fill the arrays :S

  5. #5
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    It is giving the correct result

    Well done: that's the main thing.

    but I hope my instructor does not penalize me for the 26 if statements i used to fill the arrays

    I was thinking along the lines of

    Java Code:
    static int[] doCount(char[] arr) {
        int[] ret = new int['z' - 'a' + 1];
        for(char ch :arr) {
            char lower = Character.toLowerCase(ch);
            int ndx = lower - 'a';
            if(ndx >= 0 && ndx < ret.length) {
                ret[pos]++;
            }
        }
        return ret;
    }

Similar Threads

  1. How to use arrays and loops?
    By asadzarrar in forum New To Java
    Replies: 1
    Last Post: 11-01-2010, 12:04 AM
  2. Printing Two Dimensional Arrays with for loops
    By mcnam4119 in forum JCreator
    Replies: 3
    Last Post: 10-06-2010, 06:27 AM
  3. A few questions about arrays and loops
    By Jamison5213 in forum New To Java
    Replies: 1
    Last Post: 12-22-2009, 06:59 AM
  4. Some problems with arrays and loops
    By BHCluster in forum New To Java
    Replies: 3
    Last Post: 04-16-2008, 01:24 PM
  5. Initialization and re-assignment of arrays
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 09:38 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •