在Java中,如何计算一系列数字以找到乘积,该乘积被传递给使用可变长度参数列表的方法
这个程序应该接受一系列数字,由用户放入一个数组中。我不确定在使用我创建的方法中的数组元素时如何正确地进行计算在Java中,如何计算一系列数字以找到乘积,该乘积被传递给使用可变长度参数列表的方法,java,Java,这个程序应该接受一系列数字,由用户放入一个数组中。我不确定在使用我创建的方法中的数组元素时如何正确地进行计算 public static void main(String[] args) { Scanner sc = new Scanner(System.in); //****Sentinel**** int s; //****Do...While Statement**** do{ //****User Input**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//****Sentinel****
int s;
//****Do...While Statement****
do{
//****User Input****
System.out.println("Welcome! Please enter a 1 to continue, or 2 to exit.");
s = sc.nextInt();
System.out.println();
switch(s){
case 1:
//****Array****
ArrayList<Integer> nums;
nums = new ArrayList<>();
//****User Input****
System.out.println("Please enter 4 integers: ");
System.out.println("*************************************************");
for(int i = 0; i < 4; i++){
nums.add(sc.nextInt());//****User adds to Array****
}
System.out.println("*************************************************");
//****Call Method****
Product();
break;
}
}while(s != 2);//****end Do...While****
}
//****Product Method****
public static void Product(int... nums){
//****variables****
int result;
int sum = 0;
//****iterate through array****
for(int n : nums){
sum += n;
}
//****Multiply****
int product = (sum * nums.length);
result = product;
//****User Output****
System.out.println("The product of the numbers is: " + result);
System.out.println();
System.out.println("*************************************************");
}
publicstaticvoidmain(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
//****哨兵****
int-s;
//****在陈述****
做{
//****用户输入****
System.out.println(“欢迎!请输入1继续,或输入2退出”);
s=sc.nextInt();
System.out.println();
开关{
案例1:
//****排列****
ArrayList nums;
nums=新的ArrayList();
//****用户输入****
System.out.println(“请输入4个整数:”);
System.out.println(“*******************************************************************”);
对于(int i=0;i<4;i++){
nums.add(sc.nextInt());//****用户添加到数组中****
}
System.out.println(“*******************************************************************”);
//****调用方法****
产品();
打破
}
}while(s!=2);//**end Do…while****
}
//****乘积法****
公共静态无效积(int…nums){
//****变数****
int结果;
整数和=0;
//****遍历数组****
用于(整数n:nums){
总和+=n;
}
//****倍增****
整数乘积=(总和*nums.length);
结果=产品;
//****用户输出****
System.out.println(“数字的乘积为:“+结果”);
System.out.println();
System.out.println(“*******************************************************************”);
}
我得到的唯一输出是0。您没有将数组传递给您的方法
//****Call Method****
Product();
您应该在那里传递数组。是时候使用调试器来找出代码不起作用的原因了。您是如何做到的?@BroSki12:如何通过方法参数将信息传递到方法中是Java最基本的问题,如果您问到这一点,则表明您需要查看大多数Java入门教程中的方法部分。请考虑检查相关链接。