-2

I have to make a program that reads a file and keeps track of how many of each printable character there are. I have it all down except at the end I need to display the total amount of printable characters. I don't know how to add all the array values together to get that:

public static void main(String[] args) throws IOException   {
  final int NUMCHARS = 95;


  int[] chars = new int[NUMCHARS];

  char current;   // the current character being processed

    // set up file output
    FileWriter fw = new FileWriter("output.txt"); // sets up a file for output
    BufferedWriter bw = new BufferedWriter(fw); // makes the output more efficient. We use the FileWriter (fw) created in previous line
    PrintWriter outFile = new PrintWriter(bw); // adds useful methods such as print and println

    // set up file for input using JFileChooser dialog box
    JFileChooser chooser = new JFileChooser(); // creates dialog box
    int status = chooser.showOpenDialog(null); // opens it up, and stores the return value in status when it closes

    Scanner scan;
    if(status == JFileChooser.APPROVE_OPTION)
    {
        File file = chooser.getSelectedFile();
        scan = new Scanner (file);          
    }
    else
    {
        JOptionPane.showMessageDialog(null, "No File Choosen", "Program will Halt", JOptionPane.ERROR_MESSAGE);
        outFile.close();
        return;
    }

  while(scan.hasNextLine())
  {

      String line = scan.nextLine();

  //  Count the number of each letter occurrence
  for (int ch = 0; ch < line.length(); ch++)
  {
     current = line.charAt(ch);
     chars[current-' ']++;
  }
  //  Print the results
  for (int letter=0; letter < chars.length; letter++)
  {
     if(chars[letter] >= 1)
     {
     outFile.print((char) (letter + ' '));
     outFile.print(": " + chars[letter]);
     outFile.println();
     }
  }

  }   
  outFile.close();
  scan.close();   }
  • Are you looking for the sum of all the values in the array or how many values in the array there are? – Dando18 Feb 25 '15 at 00:30

1 Answers1

0

Based on your question I'm not sure if you're asking for the total amount of items in the array or the sum of all the values in the array.

If you are looking for the sum use this method:

public int sum(int[] array){
    int sum = 0;
    for(int i = 0; i < array.length; i++){
        sum += array[i];
    }
    return sum;
}

If you are looking for the total number of items in the array then simply use array.length

Dando18
  • 622
  • 9
  • 22