Java leetcode编译器不';我不能像eclipse那样工作

Java leetcode编译器不';我不能像eclipse那样工作,java,Java,我试图解决这个问题 使用Java 我通常在在线提交之前使用Eclipse尝试这些东西 这里我附加了Eclipse中的代码 public class PrintAnnotationExample{ public static void main(String[] args) { int index = 0; int max =0; int temp = 0; int[] test = new int[] {-2,1,-3,4,-1,2,1,-5,4}; w

我试图解决这个问题 使用Java

我通常在在线提交之前使用Eclipse尝试这些东西

这里我附加了Eclipse中的代码

public class PrintAnnotationExample{
public static void main(String[] args) {
    int index = 0;
    int max =0;
    int temp = 0;
    int[] test = new int[] {-2,1,-3,4,-1,2,1,-5,4};

    while(index<test.length) {
        temp+= test[index];
        if(temp <0) {
            while(index<test.length-1 && test[index]<0) {
                ++index;
            }
            temp = 0;
        }
        max = (max >= temp ) ? max : temp;
        ++index;
    }
    ///
    System.out.println(max);

 }
}
公共类PrintAnnotationExample{
公共静态void main(字符串[]args){
int指数=0;
int max=0;
内部温度=0;
int[]测试=新的int[]{-2,1,-3,4,-1,2,1,-5,4};

虽然(index您在Eclipse和Leetcode中执行的代码明显不同,所以您需要关注它们之间的差异……而不是(错误地)得出编译器/语言存在差异的结论

区别之一是在Eclipse版本中,
index
max
temp
是局部变量。在Leetcode版本中,它们是实例变量,不会在每次调用方法时进行初始化。如果Leetcode实例化一次类并多次调用该方法,则会导致正确的行为


可能是我脑子里对Java语义的理解有误

也许吧,也可能只是个错误

但无论如何,使用实例变量来保存方法调用的状态都是不可取的。请使用局部变量来代替:

  • 为此使用局部变量可以避免犯错误,即忘记重新初始化
  • 为此使用实例变量会使该方法不可重入;即,对该方法的并发或重叠调用会相互干扰。如果递归调用该方法,或者从多个线程调用该方法,则会出现问题

为什么
args.length-1
?@user7耶!我编辑过。谢谢!
class Solution {
public int index = 0;
public int max =0;
public int temp = 0;

public int maxSubArray(int[] nums) {

    while(index<nums.length) {//아직 배열범위 안에 있을경우
        temp+=  nums[index];
        if(temp <0) {
            while(index<nums.length-1 && nums[index]<0) {
                ++index;
            }
            temp = 0;
        }
        max = (max >= temp ) ? max : temp;
        ++index;
    }
    return max;
}