Java代码无main方法运行原因及添加main与static的正确方式咨询
Java代码疑问解答:无main方法运行及添加main方法的方式
一、第一段代码无main方法为何能运行?
这段代码无法在本地Java环境直接独立运行,它能执行的场景通常是LeetCode、牛客网这类在线编程(OJ)平台。这类平台自带测试框架:会自动创建类的实例,传入预设测试用例调用twoSum方法,无需你编写main方法作为入口。但如果在本地用javac编译、java命令运行,会直接报错——因为Java程序的执行必须以main方法作为强制入口点。
二、为第一段代码添加main方法的正确方式
原代码中的twoSum是实例方法(无static修饰),要在main方法中调用它,有两种可行方案:
方案1:将twoSum改为静态方法,直接调用
修改后代码:
class Solution { public static int[] twoSum(int[] nums, int target) { int[] result = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; } } } return result; } public static void main(String[] args) { // 自定义测试用例 int[] testNums = {2, 7, 11, 15}; int testTarget = 9; int[] result = twoSum(testNums, testTarget); // 打印结果 System.out.println("符合条件的索引:" + result[0] + " 和 " + result[1]); } }
说明:给twoSum加上static修饰符后,它就变成静态方法,和main方法属于同一类层级,无需创建对象就能直接调用。
方案2:保留原方法,创建类实例调用
修改后代码:
class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; } } } return result; } public static void main(String[] args) { // 创建Solution类的实例 Solution solution = new Solution(); // 自定义测试用例 int[] testNums = {3, 2, 4}; int testTarget = 6; int[] result = solution.twoSum(testNums, testTarget); // 打印结果 System.out.println("符合条件的索引:" + result[0] + " 和 " + result[1]); } }
说明:如果不想修改原twoSum方法,就在main里创建Solution的对象,通过对象调用实例方法即可。
你之前尝试失败的可能原因
参照第二段代码的static模式时,可能只添加了main方法,但没给twoSum加上static修饰符。因为main是静态方法,静态方法无法直接调用非静态的实例方法,编译器会报错。只要补上static或者改用实例调用的方式,就能正常运行。
内容的提问来源于stack exchange,提问作者Azi
相关产品推荐
相关产品推荐

