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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© ninjaes 中级黑马   /  2016-3-2 21:35  /  486 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

                int count=0;
                ArrayList<Integer>al=new ArrayList<Integer>();
        for(int x=1;x<=100;x++){
                for(int y=1;y<=x;y++){
                        if(x%y==0){
                                count++;
                        }
                        if(count<=2){
                            al.add(x);
                }
               
                }
        }
        System.out.println(al);
        }

3 个回复

倒序浏览
为什么最后的结果就是【1,2】 使用的双循环 有什么问题?
回复 使用道具 举报
循环有问题,首先你的count定义下外面,count的值一直在改变,当i=2的时候,2%2的时候,count已经变为3了,所以不会再有了下面是正确的代码
  1. public static void main(String[] args) {
  2.           
  3.         ArrayList<Integer>al=new ArrayList<Integer>();
  4.         for(int x=1;x<=100;x++){
  5.                 int count=0;
  6.         for(int y=1;y<=x;y++){
  7.                
  8.                 if(x%y==0){
  9.                         count++;
  10.                 }
  11.         }
  12.         if(count<=2){
  13.                 al.add(x);
  14.         }      
  15.          }
  16.         System.out.println(al);
  17.         }
  18. }
复制代码
回复 使用道具 举报
小笼包 发表于 2016-3-2 22:47
循环有问题,首先你的count定义下外面,count的值一直在改变,当i=2的时候,2%2的时候,count已经变为3了, ...

nice!!!!!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马