Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 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 Reply

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 +
                '}';
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...