java - Sum of the first and last array elements in Java
问题描述
I'm using JB IntelliJ IDEA and trying to create a program which finds the sum of the first and last elements of a randomly generated array using the sum()
method. My problem is that an error occures, please help me.
Here is my code:
package com.company;
import java.util.Random;
public class Main {
public static int sum(int[] array) {
int x = array[0];
int y = array[9];
int z = x + y;
return z;
}
public static void main(String[] args) {
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
int j = rand.nextInt(50);
System.out.println(sum());
}
}
}
and error:
Error:(15, 32) java: method sum in class com.company.Main cannot be applied to given types;
required: int[]
found: no arguments
reason: actual and formal argument lists differ in length
解决方案
** Error:(15, 32) java: method sum in class com.company.Main cannot be applied to given types;
required: int[]
found: no arguments
reason: actual and formal argument lists differ in length
Going through the Error itself says everything about the issue:
required: int[]
found: no arguments
It is saying that it required an array of data type int which is missing(no arguments) and that is why actual and formal argument lists differ in length
Hence, Sum function requires an array to be passed as a parameter.
Also, you are getting random integer value in a integer variable j = rand.nextInt(50); but not assigning it to the array which is just wasting the loop to run unnecessarily 10 times.
Instead of assigning it to j we can directly assign it to the array and fill array with the random integers before passing it to the method sum(array):
Try this updated code with the changes needed:
package com.company;
import java.util.Random;
public class Main {
public static int sum(int[] array) {
int x = array[0];
int y = array[9];
int z = x + y;
return z;
}
public static void main(String[] args) {
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(50);
}
System.out.println(sum(array));
}
}
推荐阅读
- excel - 数组公式根据列表检查行中的多列并查找匹配项
- c# - Azure 上的 AspNetIdentity 登录失败 - 初始化字符串的格式不符合从索引 0 开始的规范
- java - 有没有办法将动作与发生在任何地方的特定异常相关联?
- reactjs - 如何测试动态页面标题?
- java - 使用 JSF+Spring-Boot、PrimeFaces 和 Joinfaces 扫描坏幻数的类路径
- typescript - 对于打字稿中的黄瓜数据表,始终返回 true
- django - 如何提高 django 中的导入处理速度?
- batch-file - 在命令提示符中键入变量输入后,如何将变量输入保存到原始批处理文件中?
- c# - MultiBinding 列上的 WPF DisplayMemberBinding
- c# - 如何在 IIS 托管的 C# web 服务中强制访问控制允许来源