A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 付星 黑马帝   /  2012-1-3 17:40  /  2376 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class Creator {
        public static void main(String[] args) {
                for (int i = 0; i < 100; i++)
                        Creature creature = new Creature();//这里不能编译,为什么?
                System.out.println(Creature.numCreated());
}
}

class Creature {
        private static long numCreated = 0;

        public Creature() {
                numCreated++;
        }

        public static long numCreated() {
                return numCreated;
        }
}

7 个回复

倒序浏览
本帖最后由 李盈科 于 2012-1-3 17:51 编辑

改完了 看一下
  1. public class Creator {
  2.     public static void main(String[] args) {
  3.             for (int i = 0; i < 100; i++)
  4.            {
  5.                     Creature creature = new Creature();
  6.             }//加上括号
  7.             System.out.println(Creature.numCreated());
  8. }
  9. }
复制代码
局部变量的作用范围是在一个块内,也可以理解为在{ }内。for 循环可以不使用{ }的,但仅限于
执行语句(其中并不包括变量声明语句)。

评分

参与人数 1技术分 +1 收起 理由
吴上储 + 1

查看全部评分

回复 使用道具 举报
for (int i = 0; i < 100; i++)
                       Creature creature = new Creature();//这里不能编译,为什么?


你在for循环里面的代码相等于执行了100次的:
Creature creature = new Creature();
Creature creature = new Creature();
Creature creature = new Creature();
Creature creature = new Creature();
Creature creature = new Creature();
……

creature 引用变量重复了啊!!!!!
回复 使用道具 举报
public class Creator {
        public static void main(String[] args)
        {
                for (int i = 0; i < 100; i++)
               {        Creature creature = new Creature();//这里不能编译,为什么?
                        System.out.println(Creature.numCreated());
                }       
        }
}

class Creature {
        private static long numCreated = 0;

        public Creature() {
                numCreated++;
        }

        public static long numCreated() {
                return numCreated;
        }
}
运行结果:1到100,这是你要的结果吗?如果是话,那你是错误就是for(){}这里两行代码没有上{}。上了之后就是你要的结果,我加上{}运行了,没问题

评分

参与人数 1技术分 +1 收起 理由
吴上储 + 1

查看全部评分

回复 使用道具 举报
  1. public class Creator {
  2.         public static void main(String[] args) {
  3.                 for (int i = 0; i < 100; i++) {// for循环没有括号
  4.                         Creature creature = new Creature();
  5.                         System.out.println(Creature.numCreated());
  6.                 }
  7.         }
  8. }

  9. class Creature {
  10.         private static long numCreated = 0;

  11.         public Creature() {
  12.                 numCreated++;
  13.         }

  14.         public static long numCreated() {
  15.                 return numCreated;
  16.         }

  17. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
吴上储 + 1

查看全部评分

回复 使用道具 举报
循环创建一个叫做 creature的对象,对象重复当然不能编译了
回复 使用道具 举报
沈样 黑马帝 2012-1-3 22:40:22
7#
是偱环在内存中创建同一个对象实例
回复 使用道具 举报
偱环在内存中创建同一个对象实例
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马