Issue
I am trying to print the array in my program with brackets and commas. Here is my code:
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
}
The format I am looking for is something like [1, 2, 3, 4, 5, 6]. If anyone one could give me some pointers then that would be great. Thank you!
Solution
Arrays.toString can do it for you.
More generally, joiners are intended for that :
System.out.println(
Arrays.stream(array)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", ", "[", "]")));
Bonus : compute the sum with Arrays.stream(array).sum();
Answered By - Arnaud Denoyelle