Java 为什么这个代码不能运行?

Java 为什么这个代码不能运行?,java,Java,我相信这可能是一个愚蠢的错误。有人想纠正我吗 public class Test1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int n = 4; public void f(int n){ System.out.print(n); if(n<=1) ret

我相信这可能是一个愚蠢的错误。有人想纠正我吗

public class Test1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
int n = 4;

public void f(int n){
 System.out.print(n);
 if(n<=1)
  return;
  else{
      f(n/2);
      f(n/2);
      }
   }
 }

不能在Java中的方法中声明方法。在公共无效查找之前,您在某处丢失了一个}。请执行以下操作:

public static void main(String[] args)
{
    // TODO code application logic here
    int n = 4;

    f(n);  
}

public void f(int n)
{
    System.out.print(n);

    if( n <= 1)
    {
      return;
    }
    else
    {
        f(n/2);
    }
}

结构需要有所不同,请尝试以下方法:

public class Test {

    public static void main(final String[] args) {
        f(4);
    }

    public static void f(final int n) {
        System.out.print(n);
        if (n <= 1) {
            return;
        } else {
            f(n / 2);
            f(n / 2);
        }
    }
}

因为对于编译器,您的代码如下所示

public class Test1 {

    public static void main(String[] args) {
        int n = 4;


        public void f(int n) {
            System.out.print(n);
            if (n <= 1)
                return;
            else {
                f(n / 2);
                f(n / 2);
            }
        }
    }
所以它有两个错误

1您正在尝试在main中的方法f中创建方法


2 no}在类的末尾

因为您有一个语法错误,编译器应该在您尝试编译它时告诉您。它指向我尝试运行的方法。。。线程main java.lang.RuntimeException中的异常:不可编译的源代码-在公共void fint n lineHint处非法启动表达式提示:计算{字符数和}字符数。它们应该是一样的。不要跳过大括号,因为你可以-总是使用大括号。因此,在if子句的第一部分添加一对。它使代码更具可读性。另外,你的缩进是不均匀的-确保每个{与其对应的}对齐。这会给我一个错误,但是如果我将其更改为静态方法,那么它就可以了。。。为什么?因为要使用f方法,必须实例化声明它的类的实例。把它设为静态没有必要,是的,因为没有实例。
public class Test1 {

    public static void main(String[] args) {
        int n = 4;


        public void f(int n) {
            System.out.print(n);
            if (n <= 1)
                return;
            else {
                f(n / 2);
                f(n / 2);
            }
        }
    }