当前位置: 代码迷 >> 综合 >> Java 不能在方法内部直接定义另一个方法
  详细解决方案

Java 不能在方法内部直接定义另一个方法

热度:49   发布时间:2024-01-15 13:00:29.0

有一段时间没有看Java,基础知识遗忘了不少。出于尽快熟悉的目的,几天来跟着教程做一些小题目的代码敲写。今天码字时犯了一个低级错误,详见如下。

//实现矩阵转置
public class ArrayRowColumnSwapDemoWrong {public static void main(String[] args) {int[][] array = new int[][] {
   {1,2,3},{4,5,6},{7,8,9}};System.out.println("矩阵转置前:");printArray(array);int[][] array_1 = new int[array[0].length][array.length];for(int i=0; i<array.length; i++) {for(int j=0; j<array[i].length; j++) {array_1[j][i] = array[i][j];}}System.out.println("矩阵转置后:");printArray(array_1);//打印矩阵元素
private static void printArray(int[][] arr) {for(int i=0; i<arr.length; i++) {for(int j=0; j<arr[i].length; j++) {System.out.print(arr[i][j]+"\t");}System.out.println();}
}
}}

代码是为了实现矩阵的转置,构造了printArray方法来打印矩阵元素。但是编译时报错

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method printArray(int[][]) is undefined for the type ArrayRowColumnSwapDemoWrong
    The method printArray(int[][]) is undefined for the type ArrayRowColumnSwapDemoWrong
    void is an invalid type for the variable printArray
    Syntax error on token "(", ; expected
    Syntax error on token ")", ; expected

报错显示printArray方法未定义,变量printArray数据类型不能为void 

接下来我尝试着将printArray方法放在main()方法上面,编译运行均正确。因为Java中并不存在先定义才能调用的问题,再根据报错中将printArray方法视作变量,可能意味着printArray方法放在了main方法内部,所以被视作了变量。回头一看果然是这个情况,于是将printArray方法抽出放在了main方法下面,这下就通过了。

再搜了一下资料,果然,是不能在方法内部直接定义方法的。但是可以在方法内部定义一个类,再在类里面定义方法。具体可见其它帖子。

将printArray方法抽出放在main方法下面,编译运行通过

public class ArrayRowColumnSwap {public static void main(String[] args) {int[][] array = new int[][] {
   {1,2,3,4},{4,5,6,7},{7,8,9,10}};System.out.println("矩阵转置前:");printArray(array);int[][] array_1 = new int[array[0].length][array.length];for(int i=0; i<array.length; i++) {for(int j=0; j<array[i].length; j++) {array_1[j][i] = array[i][j];}}System.out.println("矩阵转置后:");printArray(array_1);}private static void printArray(int[][] arr) {for(int i=0; i<arr.length; i++) {for(int j=0; j<arr[i].length; j++) {System.out.print(arr[i][j]+"\t");}System.out.println();}}}