在Java中使用括号和逗号显示数组输出?
问题描述:
我想用括号和逗号在我的程序中打印数组。这里是我的代码:在Java中使用括号和逗号显示数组输出?
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]。 如果有人能给我一些指示,那么这将是很好的。 谢谢!
答
Arrays.toString能为你做到这一点。
更一般地,加入者意为:
System.out.println(
Arrays.stream(array)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", ", "[", "]")));
奖励:计算与Arrays.stream(array).sum();
答
你可以尝试这样的事情,如果你想实现它自己:
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("]");
答
总和只看到数据结构概念上的Java它将给你更多的帮助。!。! java API提供了特殊的类来存储和操作对象组。其中一类是ArrayList的
注意的ArrayList类是java.util.ArrayList中
创建一个ArrayList,就像任何对象。
import java.util.ArrayList;
//..
ArrayList ajay = new ArrayList();
这里
的ArrayList - >类
阿贾伊 - >对象
您可以选择指定的容量和对象的类型的ArrayList将持有:
ArrayList ajay<String> = new ArrayList<String>(10);
Arraylist类为操作对象提供了许多有用的方法TS ..
的的add()方法增加了新的对象到ArrayList.And 删除()方法从列表中删除的对象..
示例代码:
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上的ials .. 谢谢。
首先downvote,hooray! – AvenNova
你现在得到什么?你需要把更多的信息放在这个问题上 – techspider