尝试在 Java 中使用静态变量时出现标识符异常

Posted

技术标签:

【中文标题】尝试在 Java 中使用静态变量时出现标识符异常【英文标题】:Getting an identifier exception when trying to use a static variable in Java 【发布时间】:2022-01-21 03:33:53 【问题描述】:

我正在学习递归,我正在尝试创建一个没有循环的reverseString 方法。声明要操作的变量时,出现以下两个错误:

MyClass.java:2: error: <identifier> expected
    int static count = 1;
       ^
MyClass.java:2: error: <identifier> expected
    int static count = 1;
                    ^
2 errors

有人知道为什么吗?这是我的代码:

public class MyClass 
    int static count = 1;
    public static String reverseString(String str) 
        String reverse = "";
        String sub = str.substring(str.length() - count, str.length() - count + 1);
        reverse += sub;
        if (sub.length() != 1) 
            return reverseString(str.substring(0, str.length() - count));
         else 
            return reverse;
        
        count++;
    
    
    public static void main(String args[]) 
      System.out.println(reverseString("Hello"));
    

【问题讨论】:

"int static ..." -> static int ... 【参考方案1】:

修饰符(如static)应位于类型之前:

static int count = 1;

【讨论】:

以上是关于尝试在 Java 中使用静态变量时出现标识符异常的主要内容,如果未能解决你的问题,请参考以下文章