查找Java数组的总和

时间:2015-02-25 00:24:53

标签: java arrays

我必须创建一个程序来读取文件并跟踪每个可打印字符的数量。除非在最后我需要显示可打印字符的总数,否则我已经完成了所有操作。我不知道如何将所有数组值一起添加到:

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();   }

1 个答案:

答案 0 :(得分:0)

根据您的问题,我不确定您是否要求数组中的项目总数或数组中所有值的总和。

如果您正在寻找总和使用此方法:

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

如果您要查找数组中的项目总数,请使用array.length