有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

查找Java数组的和

我必须制作一个程序来读取一个文件,并记录每个可打印字符的数量。我把它都记下来了,除了在最后我需要显示可打印字符的总量。我不知道如何将所有数组值相加得到:

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) 个答案

  1. # 1 楼答案

    根据你的问题,我不确定你是在问数组中的项目总数还是数组中所有值的总和

    如果您正在寻找总和,请使用以下方法:

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

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