【问题标题】:Passing variables through loops [closed]通过循环传递变量[关闭]
【发布时间】:2014-10-24 14:45:57
【问题描述】:

我相信x全局,不幸的是我无法在另一个循环内的循环内与y 分享它的价值。

公开课 A {

static int[] num = {1,4,1};
static int x , y;   

public static void main(String[] args) {

    firstLoop();
}

public static void firstLoop(){

    for (A.x = 0; A.x< num.length; A.x++ ) {

        System.out.println(" nums : " + num[A.x] );

                for ( A.y = A.x; A.y < num.length;A.y++) {

                    System.out.println(" for2 : " + A.x + " " + A.y);                   
                }
    }
}

}

【问题讨论】:

  • 很抱歉,我不知道您要做什么或要问什么。请花时间添加更多详细信息和具体问题。还请花时间格式化您的代码(并使可编译代码),尤其是您的大括号。
  • 你为什么这么认为?你的问题在哪里?
  • 写完整的代码以便我们编译。然后解释你得到了什么错误、异常或输出,以及问题所在。如果没有看到代码,我们将无法提供帮助。

标签: java loops variables


【解决方案1】:

您只能在static 方法中访问static

因此,您应该将非静态变量 int x, y 更改为 static int x, y,或者您可以通过创建类的实例来访问:

public class B {

   int x,y;
    public static void main(String[] args) {

        B b=new B();
        System.out.println(b.x+" "+b.y);

    }

}

【讨论】:

    【解决方案2】:

    当您执行y = x 时,x 是循环变量,而不是第一类。

    如果您将x 设为静态变量,则可以改用a.x(其中a 是类名)。

    public class Example {
        private static int x;
        public static void access() {
            for (int x = 0; x < name.len[x]; x++) {
                for (int y = Example.x; y < text.len[y]; y++) {
    
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多