Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

"WordPairs" I'm trying to compare 2 words in an ArrayList in Java

I'm trying to get the number of matched words in an ArrayList in my Java program

This is the whole thing: The problem is with the numMatch class:

import java.util.*;
    
public class WordPairsList {
    
    private ArrayList<WordPair> allPairs;
    
    public WordPairsList(String[] words)
    {
        allPairs = new ArrayList<WordPair>();
             
        for (int i = 0; i < words.length - 1; i++){
            for (int j = i + 1; j < words.length; j++){
                if (j == i){
                    allPairs.add( new WordPair(words[i], words[j]));
                }
            }
        }
    }
    
    public int numMatches() {
    
             /* in here I need to have a for loop that goes through the ArrayList allPairs and for
    each WordPair in allPairs, it checks to see if its first word (using the getFirst() method)
    equals the second word (using the getSecond() method). If there is a match, it increments a
    counter which it returns at the end of the method. To test this method, add another “there” into
    the words array and then uncomment the call to numMatches().
    */
        return 0;
    }
         
    public String getFirst() {
        return allPairs.getFirst();
    }

    public String getSecond() {
        return allPairs.getSecond();
    }
    
    public String toString() {
        return allPairs.toString();
    }
    
    public static void main(String[] args) {
         String[] words = {"Hi", "there", "Tyler", "Sam"};
         WordPairsList list = new WordPairsList(words);
         System.out.println(list);
         //For second part below, uncomment this test:
         System.out.println("The number of matched pairs is: " + list.numMatches());
    }
}
    
class WordPair {
    private String word1;
    private String word2;
    
    public WordPair(String w1, String w2) {
        word1 = w1;
        word2 = w2;
    }

    public String getFirst() {
        return word1;
    }

    public String getSecond() {
        return word2;
    }

    public String toString() {
        return "(" + word1 + ", " + word2 + ")";
    }
}

So I need help with how to call the getFirst() and getSecond() Methods and how to compare them using a for loop! I also don't know how to set a counter to count how many similar words are there! can you please help me!

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...