如何在Java方法中调用数组参数并传入测试数值获取结果?
解决方法
你的代码里main方法直接调用solution()会报错,因为solution是Solution内部类的非静态实例方法,而且需要传入int[] array和int height两个参数。下面给你两种可行的修改方式:
方式一:创建Solution类的实例调用方法
直接在main方法里实例化Solution类,然后传入测试用的数组和身高值,代码如下:
public class Main { static class Solution { public int solution(int[] array, int height) { int answer = 0; for (int i = 0; i < array.length; i++) { if (array[i] > height) { answer++; } } return answer; } } public static void main(String[] args) { // 1. 创建Solution类的实例 Solution sol = new Solution(); // 2. 定义测试用的数组和身高值 int[] testArray = {150, 160, 170, 180}; int testHeight = 165; // 3. 调用方法并打印结果 int result = sol.solution(testArray, testHeight); System.out.println("结果:" + result); } }
方式二:将solution方法改为静态方法
如果不想创建实例,可以把solution方法改成静态方法,这样就能直接在main里调用:
public class Main { static class Solution { // 加上static修饰符,变成静态方法 public static int solution(int[] array, int height) { int answer = 0; for (int i = 0; i < array.length; i++) { if (array[i] > height) { answer++; } } return answer; } } public static void main(String[] args) { // 直接通过类名调用静态方法,传入参数 int[] testArray = {150, 160, 170, 180}; int testHeight = 165; int result = Solution.solution(testArray, testHeight); System.out.println("结果:" + result); } }
两种方式都能正常运行,你可以根据自己的习惯选择。运行后控制台会输出符合条件的元素数量(比如上面的测试用例,身高大于165的是170和180,结果会输出2)。
内容的提问来源于stack exchange,提问作者maricenaz
相关产品推荐
相关产品推荐

