1

我有一个生成 9 个随机数的方法,至少我将它们存储在一个字符串中以显示在控制台上。这是功能:

public static String GenerateNumbers(){
    int[] NumberList = new int[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String[] ar = Arrays.toString(NumberList).split("[\\[\\]]")[1].split(", ");
    String a = Arrays.toString(ar);
    return a;
}

当我在控制台上看到这个字符串时,就像:[20, 28, 33, 46, 46, 57, 81, 83, 90]

我需要看到的是:[20 28 33 46 46 57 81 83 90]

如果: 20 28 33 46 46 57 81 83 90

4

5 回答 5

1

使用TextUtils.join()将数组与 a CharSequence(也可以String)连接起来。

public static String GenerateNumbers(){
    Integer[] NumberList = new Integer[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String a = TextUtils.join(" ",NumberList);
    return a;
}
于 2013-11-08T09:56:27.733 回答
1

在返回字符串之前添加一行代码,您将获得完美的输出:

public static String GenerateNumbers(){
    int[] NumberList = new int[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String[] ar = Arrays.toString(NumberList).split("[\\[\\]]")[1].split(", ");
    String a = Arrays.toString(ar);

    //add this line to remove characters you don't need
    a = a.replace("[", "").replace(",", "").replace("]", "");

    return a;
}
于 2013-11-08T10:21:28.120 回答
1

像这样改变你的方法..

public static String GenerateNumbers() {
    int[] NumberList = new int[9];
    for (int i = 0; i < 9; i++) {
        NumberList[i] = (int) Math.floor(Math.random() * (100 - 10 + 1)
                + 10);
    }
    Arrays.sort(NumberList);
    String a = Arrays.toString(NumberList);
    a = a.replaceAll(",", "");
    a = a.replaceAll("[\\[\\]]", "");
    return a;
}

输出:

16 28 30 37 45 70 73 85 92
于 2013-11-08T10:10:41.653 回答
1

这可能会帮助你

public static void main(String[] args) {
    String a = "[20, 28, 33, 46, 46, 57, 81, 83, 90]";
    String b = a.substring(a.indexOf("[")+1, a.indexOf("]"));
    StringTokenizer token = new StringTokenizer(b, ",");
    while(token.hasMoreElements()){
        System.out.print(token.nextElement());
    }
}


//output
20 28 33 46 46 57 81 83 90
于 2013-11-08T10:01:19.137 回答
1

用这个,

public static String GenerateNumbers(){
    int[] NumberList = new int[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String a="";
    for(int i=0;i<9;i++){
        a+= NumberList[i]+" ";
    }
    a = a.trim();
    return a;
}
于 2013-11-08T10:01:46.250 回答