Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Return an array of Pairs which have the same length as the input array of Strings. (Java)

I want to create a class that would return an array of pairs that have the same length as the input array of strings. In addition, the pair should have the first letter of the string and length of the string.

for example; create(new String[] {"clue", "yay", "neon", "halala"}) should return the array of Pairs {[’c’,4],[’y’,3],[’n’,4],['h',6]}

So, my input and output would both be arrays. But the output has to be in the form of a pair. Here's what i tried:

import java.util.Arrays;



public class Couple {


public static Couple[] create(String[] source){

        for (int i = 0; i < source.length; i++) {

            System.out.print("["+","+source.length+"]") ;
        }
        return null;

    }            

    public static void main(String[] args) {
        System.out.println(Arrays.toString(create(new String[] {"clue", "yay", "neon", "halala"})));

    }

}

as it's obvious there are a few errors+ i dont want it to return null. But just for the sake of testing this code, i had to do it. Any ideas?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
public class Couple {

    private char firstChar;
    private int length;

    public Couple(char firstChar, int length) {
        this.length = length;
        this.firstChar = firstChar;
    }

    public static Couple[] create(String[] source) {
        Couple[] couples = new Couple[source.length]; // create the array to hold the return pairs

        for (int i = 0; i < source.length; i++) {
            String entry = source[i];
            if (entry != null) {
                couples[i] = new Couple(entry.charAt(0), entry.length());
            } else {
                // What do you want to do if there's a null value?
                // Until you answer this we'll just leave the corresponding Couple null aswell
            }
        }

        return couples;
    }

    @Override
    public String toString() {
        return "Couple{" +
                "firstChar=" + firstChar +
                ", length=" + length +
                '}';
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...