构建方法将数组转换为字符串

时间:2016-04-02 23:15:19

标签: java

我敢于创建一个方法将数组转换为int而不使用来自" Arrays"的arrays.toString()内置库。这就是我所拥有的:

import java.util.Arrays;
public class P01ArrayIntsInit {

    String arrayToString(int[] array){
        int[] n = new int[]{10,16,181,200,410,68,31,555,161,313};
        //System.out.println(Arrays.toString(n));

    }
}

我坚持应该回归的条件是什么?建议?这是一项不必要的任务的一部分,但如果我能用自己的方法来简化事情,我会毫不犹豫地使用它,因为我需要多次打印一个数组。我知道它可能是一个愚蠢的问题,但返回条件必须是一个字符串类型,我不知道如何把它。 谢谢

2 个答案:

答案 0 :(得分:1)

您可以编写自己的# define your functions first def function_left(): # do something here def function_right(): # do something here #then call your functions from the if/elif block action4 = input("Left down the hallway? Or right?") if action4 == ("left"): print ("You turn left and proceed down this hallway") function_left() elif action4 == ("right"): print ("You turn right and proceed down this hallway") function_right() 方法,例如:

toString

答案 1 :(得分:0)

有很多方法可以实现Arrays::toString,以下是一些示例:

import java.util.Arrays;
import java.util.StringJoiner;
import java.util.stream.Collectors;

public class ArraysToString {
    public static void main(String[] args) {
        int[] array = {10, 16, 181, 200, 410, 68, 31, 555, 161, 313};

        System.out.println(Arrays.toString(array));
        System.out.println(arrayToString1(array));
        System.out.println(arrayToString2(array));
        System.out.println(arrayToString3(array));
        System.out.println(arrayToString4(array));
        // [10, 16, 181, 200, 410, 68, 31, 555, 161, 313]
        // [10, 16, 181, 200, 410, 68, 31, 555, 161, 313]
        // [10, 16, 181, 200, 410, 68, 31, 555, 161, 313]
        // [10, 16, 181, 200, 410, 68, 31, 555, 161, 313]
        // [10, 16, 181, 200, 410, 68, 31, 555, 161, 313]
    }


    static String arrayToString1(int[] array) {
        StringJoiner stringJoiner = new StringJoiner(", ", "[", "]");
        for (int i : array) {
            stringJoiner.add(Integer.toString(i));
        }
        return stringJoiner.toString();
    }

    static String arrayToString2(int[] array) {
        return Arrays.stream(array)
                .mapToObj(Integer::toString)
                .collect(Collectors.joining(", ", "[", "]"));

    }

    static String arrayToString3(int[] array) {
        StringBuilder sb = new StringBuilder("[");
        String separator = "";
        for (int i : array) {
            sb.append(separator);
            sb.append(Integer.toString(i));
            separator = ", ";
        }
        sb.append("]");
        return sb.toString();
    }

    static String arrayToString4(int[] array) {
        String result = "[";
        for (int i = 0; i < array.length; i++) {
            result += array[i];
            if (i < array.length - 1) {
                result += ", ";
            }
        }
        return result + "]";
    }
}