Java 如何使用JOptionPane从数组和输出中添加整数元素?

Java 如何使用JOptionPane从数组和输出中添加整数元素?,java,arrays,joptionpane,Java,Arrays,Joptionpane,这是我的东西。用户输入7天的预约次数,但我不知道如何添加用户从数组输入的整数?有没有关于我如何做这件事的建议 import javax.swing.JOptionPane; public class AdvisingAppointmentTracker { public static void main(String[] args) { // Step 1: Set any constants needed for the program final int NUM_DAYS

这是我的东西。用户输入7天的预约次数,但我不知道如何添加用户从数组输入的整数?有没有关于我如何做这件事的建议

import javax.swing.JOptionPane;

public class AdvisingAppointmentTracker {
   public static void main(String[] args) {

  // Step 1: Set any constants needed for the program
  final int NUM_DAYS = 7;
  final int MIN_NUM_APPOINTMENTS = 0;

  // Step 2: Create an array that will hold the number of advising appointments per day
  int appointments[] = new int[NUM_DAYS];

  // Step 3: Enter the number of advising appointments for all of the days      
  for(int i = 0; i < appointments.length; i++)
     appointments[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of appointments"));
  // Step 4: Find the average number of appointments


  // Step 5: Output the average number of appointments

  }   
}
import javax.swing.JOptionPane;
公共类咨询AppointTracker{
公共静态void main(字符串[]args){
//步骤1:设置程序所需的任何常量
最终整数天数=7天;
最终int MIN_NUM_约会=0;
//步骤2:创建一个数组,该数组将保存每天的通知约会数
整数约会[]=新整数[天数];
//第3步:输入所有日期的通知约会次数
for(int i=0;i<0.length;i++)
约会[i]=Integer.parseInt(JOptionPane.showInputDialog(“输入约会次数”);
//第4步:查找平均预约次数
//步骤5:输出平均预约次数
}   
}
这是一种方法

int numberOfAppointments = 0;
for(int appointment : appointments){
    numberOfAppointments += appointment;
}        
JOptionPane.showMessageDialog(null, numberOfAppointments / appointments.length);

这里是一个循序渐进的教程

首先,创建一个存储数组元素总数的变量

int sum = 0;
那么,这是最难的部分

你知道如何用这个循环一个数组吗

for(int i = 0; i < appointments.length; i++)
这正是你应该做的!你应该把这两者结合起来

for(int i = 0; i < appointments.length; i++)
    sum += appointments[i];
正如您在这里看到的,如果您使用这种循环,就不需要再编写
appointment[i]
。您可以将其替换为约会

现在,您可以非常轻松地计算平均值:

int average = sum / (double)appointments.length;

“等一下!为什么
(双倍)
?”你问。事实上,这是没有必要的。只有当您想要得到一个小数位数的结果时,才需要这个值,因为
int
除以
int
总是
int

您是否在询问如何添加/使用数组中的数字?在代码中再次使用相同的for循环。如何?我尝试过使用int-total+=约会;但我得到的错误是,它不是一个语句。您需要包含数组括号才能访问存储的数字<代码>总计+=约会[i]将起作用。您还可以对(int n:约会)total+=n执行

for (int appointment : appointments)
    sum += apppointment;
int average = sum / (double)appointments.length;