美文网首页
20、for循环的另一种写法

20、for循环的另一种写法

作者: 爱学习的代代 | 来源:发表于2021-04-02 09:23 被阅读0次

    之前我们使用for循环的时候一般是诸如for (int i = 0; i < 10; i++)这样的一种方式,当我们不关心元素的次序,需要把一个列表里的所有元素遍历一遍呢?

    实例: 一个超市初始化10件商品,输出每件商品的重要信息。

    package day13;
    
    import day12.Merchandise;
    
    public class SuperMarket {
        String name;
        String location;
        MerchandiseWithConstructor[] merchandiseWithConstructors;
    
        public SuperMarket(String name, String location, int merchandiseCount) {
            this.name = name;
            this.location = location;
            merchandiseWithConstructors = new MerchandiseWithConstructor[merchandiseCount];
    
            String[] names = {"毛巾","茶杯","袜子","纸巾","牙膏","牙刷","瓜子","泡面","苹果","香蕉"};
    
    
            for (int i = 0; i < 10; i++) {
                int count = (int)(Math.random() * 10 + 2);
    
                double soldPrice = (int)((Math.random() * 10 +10) * 100) / 100 ;
                double purchesePrice = (int)((Math.random() * 10 + 3) * 100) / 100;
                MerchandiseWithConstructor x = new MerchandiseWithConstructor(i,names[i],count,soldPrice,purchesePrice);
                if (x instanceof MerchandiseWithConstructor) {
                    merchandiseWithConstructors[i] = x;
                }
            }
        }
    
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getLocation() {
            return location;
        }
    
        public void setLocation(String location) {
            this.location = location;
        }
    
        public MerchandiseWithConstructor[] getMerchandise() {
            return merchandiseWithConstructors;
        }
    
        public void setMerchandise(MerchandiseWithConstructor[] merchandise) {
            this.merchandiseWithConstructors = merchandise;
        }
    }
    
    

    测试代码

    package day13;
    
    import day12.Merchandise;
    
    public class TestSuperMarket {
        public static void main(String[] args) {
    
            SuperMarket s = new SuperMarket("如海超市","中科路888号",10);
    
            for (MerchandiseWithConstructor m: s.merchandiseWithConstructors) {
                m.describe();
            }
    
    
    
        }
    }
    
    

    程序运行结果:


    image.png

    说明: 当我们不关心循环的次序的时候,可以使用类名 + 变量名 + : + 要循环的列表 实现。

            for (MerchandiseWithConstructor m: s.merchandiseWithConstructors) {
                m.describe();
            }
    

    相关文章

      网友评论

          本文标题:20、for循环的另一种写法

          本文链接:https://www.haomeiwen.com/subject/kmcohltx.html