Java从嵌套的for循环重复输出 [英] Java Repeated output from nested for loop

查看:99
本文介绍了Java从嵌套的for循环重复输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个程序包,问题是当运行时,它在容器之间重复相同的目录条目. 我认为问题出在detailInventory方法中. 应该:它应该为Bin B创建一个新的随机bin项目(类型,标题,艺术家),而不使用Bin A中的相同元素.除此之外,输出正确. SKU编号已正确生成并显示.

I created this package, and the problem is when is runs it repeats the same catalog entries between bins. I think the problem is in the detailedInventory method. SHOULD BE: It should create a new random bin item (type, title, artist) for Bin B, not use the same element from Bin A. Other than this, the output is correct. SKU numbers are correctly generated and displayed.

** i的值(当它们对应于目录时)是对象.它们实际上是具有标题,艺术家和SKU属性的不同类型的物理媒体,例如DVD或盒式磁带.

**The values of i, when they correspond to the catalog, are objects. they are actually different types of physical media, such as DVDs or cassettes, with title, artist and SKU attributes.

***尽管这似乎没有意义,但是应该随机生成数据. (该类是更大的概念/课程的一部分,用于说明继承.)

***Although it does not seem to make sense, the data should be generated randomly. (This class is part of a larger concept/lesson to illustrate inheritance.)

任何帮助将不胜感激!

这是我看到的输出:


Bin A:
DVD - Greatest Hits Volume 2 (Limp Bizkit), SKU 1234-0: 500
Cassette - The Best Of (Michael Jackson), SKU 1234-1: 25
DVD - Love Songs (Michael Jackson), SKU 1234-2: 7720
Bin B: DVD - Greatest Hits Volume 2 (Limp Bizkit), SKU 1234-3: 1000

Bin B下的bin项目不应与A相同.

The bin item under Bin B should not be the same as A.

public class testMusicMedia
{
    public static ArrayList<MusicMedia> MakeMusicCatalog( int size )
    {
       String[] titles =
         {
           "Greatest Hits Volume 1", "Greatest Hits Volume 2",
           "The Best Of", "Love Songs",
           "The Early Years", "The Later Years"
         };
       String[] artists = 
         {
           "Michael Jackson", "Eminem",
           "The Beatles", "Shania Twain",
           "Limp Bizkit"
         };
       ArrayList<MusicMedia> catalog = new ArrayList<MusicMedia>();
       Random rn = new Random();
       for ( int i = 0 ; i < size ; i++ )
       {
            MusicMedia m;
            int mediatype = rn.nextInt( 3 );
            String title = titles[ rn.nextInt( titles.length ) ];
            String artist = artists[ rn.nextInt( artists.length ) ];
            String sku = "1234-" + i;
            if ( mediatype == 0 )
                m = new CompactDisk( title, artist, sku );
            else if ( mediatype == 1 )
                m = new DigitalVideoDisk( title, artist, sku );
            else
                m = new CassetteTape( title, artist, sku );
            catalog.add( m );
       }
      return catalog;
    }   

    public static String lookupMedia( ArrayList<MusicMedia> catalog,
        String sku )
    {
        for ( MusicMedia m : catalog )
        {
            if ( m.getSKU().equals( sku ))                  
            return "SKU is in catalog";
        }
        return "SKU not in catalog";
    }

    public static String detailedInventory( ArrayList<MusicMedia> catalog, ArrayList<Bin> warehouse )
    {
        String s = "";
        for ( Bin bn : warehouse ){
            s += "Bin " + bn.getName() + ":\n"; 
              for (int i = 0; i < bn.getContents().size(); i++){
                s += catalog.get(i) + ", " + bn.getContents().get(i) + "\n";
              }
        }
        s += "\n";
        return s;
    }  

    public static void main( String[] args )
    {
        ArrayList<MusicMedia> catalog = MakeMusicCatalog( 10 );
        ArrayList<Bin> warehouse = new ArrayList<Bin>();
        Bin a = new Bin( "A" );
        Bin b = new Bin( "B" );
        warehouse.add( a );
        warehouse.add( b );
        a.add( new BinItem( "1234-0", 500 ) );
        a.add( new BinItem( "1234-1", 25 ) );
        a.add( new BinItem( "1234-2", 7720 ) );
        b.add( new BinItem( "1234-3", 1000 ) );
        System.out.println( detailedInventory( catalog, warehouse ) ); 
    }
} 

我将共享同一SKU的垃圾箱中所有项目的集合称为垃圾箱项目". Bin类的每个对象(未显示)代表一个假装仓库中的一个bin. Bin对象具有两个实例变量:包含bin名称的String和包含bin中存储的每个SKU的BinItem的ArrayList. Bin类的toString方法使用BinItem类的toString方法.它会生成仅涉及SKU和数量的列表.

I call the collection of all the items in a bin that share the same SKU a "bin item". Each object of the Bin class (not shown) represents a bin in a pretend warehouse. A Bin object has two instance variables: a String that contains the bin name and an ArrayList that contains a BinItem for each of the SKUs stored in the bin. The toString method of the Bin class uses the toString method of the BinItem class. It generates lists that only involve SKUs and quantities.

此方法应使用for-each循环来循环遍历仓库中的所有垃圾箱.对于每个bin,应使用字符串"Bin"扩展s,后跟bin的名称,后跟冒号和\ n以开始新行.然后,它应该循环浏览当前bin中的所有bin项目,对于每个项目 以新的一行文本扩展s,该文本的开头是在输入目录中查找当前bin项目的SKU的结果,然后以逗号开头,后跟bin项目的String表示形式.

This method should use a for-each loop to cycle thorugh all the bins in the warehouse. For each bin, s should be extended by the String "Bin " followed by the name of the bin, followed by a colon and \n to start new line. Then it should cycle through all the bin items in the current bin, for each one extending s by a new line of text that begins with the result of looking up the current bin item’s SKU in the input catalog, and continue with a comma followed by the String representation of the bin item.

输出应如下所示:


Bin A:
CD - The Later Years (Shania Twain), SKU 1234-0: 500
Cassette - Greatest Hits Volume 2 (The Beatles), SKU 1234-1: 25
Cassette - Greatest Hits Volume 1 (Shania Twain), SKU 1234-2: 7720

Bin B: Cassette - Greatest Hits Volume 2 (Michael Jackson), SKU 1234-3: 1000

完整代码:

public class MusicMedia
{
    private String myTitle,
    myArtist,
    mySKU;

    public MusicMedia( String title, String artist, String sku )
    {
        myTitle = title;
        myArtist = artist;
        mySKU = sku;
   }
   public String getTitle()
   {
       return myTitle;
    }
    public String getArtist()
    {
        return myArtist;
    }
    public String getMediaType()
    {
        return "Unknown";
    }
    public String getSKU()
    {
        return mySKU;
    }
    public String toString()
    {
        return " - " + getTitle() + " (" + getArtist() + ")";
    }
}


  public class Disk extends MusicMedia
{
    /**
     * Constructor for objects of class Disk
     */
    public Disk( String title, String artist, String sku )
    {
        super(title, artist, sku);
    }

    public String getMediaType()
    {
        return "Disk"; 
    }

    public String toString()
    {
        return getMediaType() + super.toString();
    }
}

我也有一个完全相同的CassetteTape类,它也扩展了MusicMedia.磁盘的另外两个子类称为CompactDisk和DigitalVideoDisk.这两个几乎也完全相同,因此我在下面粘贴了DVD类.

I also have an identical CassetteTape class that also extends MusicMedia. Also two other subclasses of Disk, called CompactDisk and DigitalVideoDisk. These two are also almost identical to each other, so I have pasted the DVD class below.

public class DigitalVideoDisk extends Disk
{
    /**
     * Constructor for objects of class DigitalVideoDisk
     */
    public DigitalVideoDisk( String title, String artist, String sku )
    {
        super(title, artist, sku);
    }

    public String getMediaType()
    {
        return "DVD";
    }
}
public class BinItem
{
    private String mySKU;
    private int    myQuantity;
    public BinItem( String sku, int quantity )
    {
        mySKU = sku;
        myQuantity = quantity; 
    }
    public String getSKU()
    { 
        return mySKU;
    }
    public int getQuantity()
    {
        return myQuantity;
    }
    public String toString()
    {
        return "SKU " + getSKU() + ": " + getQuantity();
    }
 }

public class Bin
{
    private String  myName; //bin name
    private ArrayList<BinItem>   myContents; //contains a binItem
    public Bin( String name )
    {
      myName = name;
      myContents = new ArrayList<BinItem>();
    }   
    public String getName()
    {
      return myName;
    }    
    public ArrayList<BinItem> getContents()
    {
        return myContents;
    }   
    public void add( BinItem b )
    {        
        myContents.add( b );
    }    
    public String toString()
    {
        String s = "Bin " + myName + ":\n";
        for ( BinItem b : myContents )
            s += b + "\n";
        return s;
    }
}

推荐答案

好的,根据您的修改:

...在输入目录中查找当前bin项目的SKU的结果...

...the result of looking up the current bin item’s SKU in the input catalog...

您现在不执行此操作,这是我们需要了解程序应该执行的操作的关键点.现在,您基本上可以任意使用icatalog检索元素.

You aren't doing this right now and it was the key point that we needed to understand what the program was supposed to do. Right now you're just retrieving an element from catalog using i, basically arbitrarily.

因此,您要做的第一件事是创建一个帮助器方法,该方法在catalog中搜索某个SKU的MusicMedia对象.您有一个非常类似于它的方法,称为lookupMedia,所以我刚刚将其修改为此稍有不同的规范.这将返回m而不是字符串值:

So the first thing you need to do is create a helper method that searches catalog for a MusicMedia object of a certain SKU. You have a method very much like it called lookupMedia so I've just modified it to this slightly different specification. This returns m instead of a String value:

public static MusicMedia getMediaBySKU(
    ArrayList<MusicMedia> catalog, String sku
) {
    for ( MusicMedia m : catalog ) {
        if ( m.getSKU().equals(sku) )
            return m;
    }
    return null;
}

现在您已经能够根据SKU检索项目,可以修改detailedInventory循环以使用它:

Now that you are able to retrieve an item based on the SKU you can modify the detailedInventory loop to use it:

for ( Bin bn : warehouse ){
    s += "Bin " + bn.getName() + ":\n";

    for ( BinItem item : bn.getContents() ){
        MusicMedia mm = getMediaBySKU(catalog, item.getSKU());

        s += mm + ", " + item + "\n";
    }
}

(不确定如何从BinItem中获取SKU,所以我想,但我希望您能理解.如果您还没有返回SKU的方法,则可能需要创建一个.)

(Not sure how to get the SKU from the BinItem so I guessed but I hope you get the idea. If you don't have a method that returns the SKU already, you probably need to make one.)

这篇关于Java从嵌套的for循环重复输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆