计算数组算法中歌曲匹配的匹配数

时间:2019-01-02 03:57:04

标签: java arrays

我花了最后六个小时来尝试解决这一小段代码,我非常感谢学习如何做到这一点。

到目前为止,我有这个数组:

public static void main ()
    {Song[] topTenSongs = {new Song("The Twist"), 
        new Song ("Smooth"),
        new Song ("Mack the Knife"),
        new Song ("How Do I Live"),
        new Song ("Party Rock Anthem"),
        new Song ("I Gotta Feeling"),
        new Song ("Macarena (Bayside Boys Mix)"),
        new Song ("Physical"),
        new Song ("You Light Up My Life"),
        new Song ("Hey Jude")
    };

    String[] tenSongNames = {"The Twist",
        "Smooth",
        "Mack the Knife",
        "How Do I Live",
        "Party Rock Anthem",
        "I Gotta Feeling",
        "Macarena (Bayside Boys Mix)",
        "Physical",
        "You Light Up My Life",
        "Hey Jude"};

        int [] songRatings = {2,8,10, 7,1,6,2,4,3,5};

我的目标是使用for-each循环来计算并列的歌曲数量,然后使用String变量和字符串连接来跟踪并列并排的Song标题。

我将如何去做?我目前有一些类似的东西:

for (Song s : topTenSongs) {
    int count = 0;
    if(s.getRating() == 2) {    
        System.out.println(count + 1);
    }
}

但是我感觉这是错误的。

谢谢!

2 个答案:

答案 0 :(得分:1)

因此,当songRatings是该索引的value==2数组中的获取歌曲时,首先迭代topTenSongs数组以保持索引的跟踪

循环

 for(int i=0; i< songRatings.length; i++){
    if(songRatings[i]== 2){
       System.out.println("The song with rating 2 is :"+ tenSongNames[i]);
         // In the same way you can get songs from `topTenSongs` array of specific index `topTenSongs[i]`
          }
     }

如果有兴趣学习Java-8,请使用IntStream

java-8 IntStream

IntStream.range(0, songRatings.length).filter(i->songRatings[i]==2).forEach(s->System.out.println(tenSongNames[s]));

forEach

int count =0;
for(int i: songRatings){
 count++;
  if(i==2){
    System.out.println("The song with rating 2 is :"+ tenSongNames[i]);
     }
   }

答案 1 :(得分:0)

我认为问题出在 int count =0 我应该在之前。因为计数总是回到2