在Java中用括号和逗号显示数组输出?

时间:2016-06-10 13:42:09

标签: java arrays formatting comma brackets

我正在尝试用括号和逗号在程序中打印数组。这是我的代码:

public static void main(String[] args) {

    int[] arrayIntList = new int[10]; // Starting the array with the specified length

    int sum = 0; // Defining the sum as 0 for now

    // Using the for loop to generate the 10 random numbers from 100 to 200, inclusive.
    for(int nums1 = 0; nums1 < arrayIntList.length; nums1++) {
        arrayIntList[nums1] = (int)(100 + Math.random()*101);
    }           

    Arrays.sort(arrayIntList); // Sorting the array list

    System.out.print("[");
    for(int i = 0; i < arrayIntList.length; i++) { // Printing the array
        System.out.print(arrayIntList[i] + " "); 
        }
    System.out.print("]");

    int[] arrayC = CalcArray(arrayIntList); // Sending the array to the method

    System.out.println("");

    for(int doubles : arrayC) { 
        System.out.print(doubles + " "); // Printing the output from the second method and calculating the sum
        sum = sum + doubles;
    }

    System.out.printf("%nThe total is %,d", sum); // Printing the sum
}

private static int[] CalcArray(int[] nums) {

    for(int nums2 = 0; nums2 < nums.length; nums2++) { // Doubling the original array
        nums[nums2] *= 2; 
    }
    return nums; // Returning the doubles numbers

}

我正在寻找的格式类似于[1,2,3,4,5,6]。 如果有人能给我一些指示,那就太棒了。 谢谢!

4 个答案:

答案 0 :(得分:3)

Arrays.toString可以为你做到。

更一般地说,加入者的目的是:

System.out.println(
    Arrays.stream(array)
        .mapToObj(Integer::toString)
        .collect(Collectors.joining(", ", "[", "]")));

奖励:使用Arrays.stream(array).sum();

计算总和

答案 1 :(得分:2)

只需使用Arrays.toString,它就会为您完成,更多详情here

答案 2 :(得分:0)

如果你想自己实现它,你可以尝试这样的事情:

int[] array = new int[]{1, 2, 3, 4, 5, 6};
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < array.length; i++) {
    sb.append(array[i]);
    if (i < array.length - 1) {
      sb.append(", ");
    }
}
sb.append("]");

答案 3 :(得分:0)

只需在java上看到Data Structures Concept。它会对你更有帮助。 java API 提供了用于存储和操作对象组的特殊类。一个这样的类是 Arraylist

请注意 Arraylist 类位于java.util.ArrayList中

像创建任何对象一样创建一个ArrayList。

import java.util.ArrayList;
//..
ArrayList ajay = new ArrayList(); 

下面

ArrayList - &gt;类

ajay - &gt;对象

您可以选择指定Arraylist将容纳的对象的容量和类型:

ArrayList ajay<String> = new ArrayList<String>(10);

Arraylist类为操作对象提供了许多有用的方法..

add()方法将新对象添加到ArrayList.And remove()方法从列表中删除对象..

示例代码:

import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
    public static void main(String[ ] args) {

        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> ajay = new ArrayList<Integer>();
        int num;
        int i;
        for(i=0;i<5;i++){
            num=sc.nextInt();
            ajay.add(num);
        }
        System.out.println(ajay);
    }
}

输入:1 2 3 4 5 输出:

[1,2,3,4,5]

如果您有疑问,请在java上学习关于ArrayList的教程。 谢谢。!