Print multi-dimensional array using foreach [duplicate] - java

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 6 years ago.
How to print multi-dimensional array using for-each loop in java? I tried, foreach works for normal array but not work in multi-dimensional array, how can I do that? My code is:
class Test
{
public static void main(String[] args)
{
int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7, 8}};
for(int[] val: array1)
{
System.out.print(val);
}
}
}

Your loop will print each of the sub-arrays, by printing their address. Given that inner array, use an inner loop:
for(int[] arr2: array1)
{
for(int val: arr2)
System.out.print(val);
}
Arrays don't have a String representation that would, e.g. print all the elements. You need to print them explicitly:
int oneD[] = new int[5];
oneD[0] = 7;
// ...
System.out.println(oneD);
The output is an address:
[I#148cc8c
However, the libs do supply the method deepToString for this purpose, so this may also suit your purposes:
System.out.println(Arrays.deepToString(array1));

If you just want to print the data contained in the int array to a log, you can use
Arrays.deepToString
which does not use any for loops.
Working Code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}};
System.out.println(Arrays.deepToString(array));
}
}
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]

This is a very general approach that works in most languages. You will have to use nested loops. The outer loop accesses the rows of the array, while the inner loop accesses the elements within that row. Then, just print it out and start a new line for every row (or choose whatever format you want it to be printed in).
for (int[] arr : array1) {
for (int v : arr) {
System.out.print(" " + v);
}
System.out.println();
}

The current output would look something like:
[I#1e63e3d
...
which shows the string representation for an integer array.
You could use Arrays.toString to display the array content:
for (int[] val : array1) {
System.out.println(Arrays.toString(val));
}

Related

Java multidimensional array layout

I am studying for an exam and this is about memory allocation of a multidimensional java array.
Given is the following code:
double [][] a = new double[4][];
for (int i = 0; i < 4; i++)
a[i] = new double[4-i];
I am supposed to draw the memory layout of this array, but I am afraid I don't fully comprehend how it even works.
It would also be very kind of you if you could show me how to print this array as list to the console so I can look at it. :)
Thank you for your time.
you don't have to create new array in the for loop. Try this:
double[][] a = new double[4][3];
Or you can initialize it in one statement like:
double[][] a = {
{1, 3, 2},
{4, 5, 6},
{7, 8, 9}
};
And then print:
System.out.println(Arrays.deepToString(a))
Since your array a is an array of array (2D) , you can use enhanced for loop to print elements.
So, your outer loop has double[] as type, and hence that declaration. If you iterate through your a in one more inner loop, you will get the type double.
double[][] a = {
{1, 3},
{4, 5},
{7, 8}
};
List<Double> dou = new ArrayList<Double>();
for (double[] k: a) {
for (double element: k) {
dou.add(element) ;
}
}
System.out.println(dou);
Output
[1.0, 3.0, 4.0, 5.0, 7.0, 8.0]
I am not sure if this answers your question.
Above picture depicts how array elements will be stored in memory.

Java take range from array

Does Java have a method of Array drop? In Scala we have: Array.drop(10).take(16) or maybe to take a range of members of an array?
In Java I can only do array[10] for example.
There is Arrays::copyOfRange:
It has three parameters:
original: the source array
from: the starting index, inclusive
to: the end index, exclusive
Not that it returns a new array, meaning that if you change the values of the resulting array, the original array does not change.
The method is overloaded to work for all primitive types and for objects.
Here's an example use:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
final int[] source = IntStream.range(0, 10).toArray()
System.out.println(Arrays.toString(source));
final int[] result = Arrays.copyOfRange(source, 3, 8);
System.out.println(Arrays.toString(result));
}
}
Which prints:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
For more information, see the docs
I think it's easiest to achieve such semantics by streaming the array:
SomeClass[] sourceArray = /* something */;
SomeClass[] result =
Arrays.stream(sourceArray).skip(10L).limit(16L).toArray(SomeClass[]::new);

Simple array class working but giving wrong output

I'm doing some Java code challenges and am trying to write the entire class w/ a constructor and main() instead of a regular method just to get some extra practice in. I've tried running it in Eclipse and JGrasp and got the same output: [I#6d06d69c
Does anyone have a clue as to what I'm doing wrong? Thanks in advance for your help :)
/*
Given an int array, return a new array with double the
length where its last element is the same as the original
array, and all the other elements are 0. The original
array will be length 1 or more. Note: by default, a
new int array contains all 0's.
makeLast({4, 5, 6}) → {0, 0, 0, 0, 0, 6}
makeLast({1, 2}) → {0, 0, 0, 2}
makeLast({3}) → {0, 3}
*/
public class MakeLast {
public MakeLast(int[]nums){
int[] result = new int[nums.length *2];
result[result.length-1] = nums[nums.length-1];
System.out.println(result);
}
public static void main(String[] args) {
int[] nums = {3, 5, 35, 23};
new MakeLast(nums);
}
}
result is an array, you cannot print it directly using System.out.println. Instead try the below.
System.out.println(Arrays.toString(result));
If you want more controlled output of the elements in the array, you can iterate through the elements in the array and print them one by one. Also you can check the javadoc for toString method in Object class to see what [I#6d06d69c means.
You can not print the array directly by System.out.println() method in java.
For that you have to use the toString() method present in Array class of util package. Moreover here you can directly use result[7] to see the value.
import java.util.*;
class MakeLast {
public MakeLast(int[]nums){
int[] result = new int[nums.length *2];
result[result.length-1] = nums[nums.length-1];
System.out.println(result.length);
System.out.println(result[7]);
System.out.println(Arrays.toString(result));
}
public static void main(String[] args) {
int[] nums = {3, 5, 35, 23};
new MakeLast(nums);
}
}

How to declare an array element null?

I am trying to find out whats happening with my code, I kept getting nullexeptionpointer problem. So I decided to reduce my code and find out whats happening. I want to remove a particular element providing the index to be removed, afterwards, moving all element after it to fill up the space left.
After moving all element, I want to set the last element in the array to null, but i get error and wont compile.
public static void main(String[] args) {
int [] charSort = new int[] {12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11};
TextIO.putln("ArrayNum = [12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11]\n");
TextIO.put("Sorted ArrayNum is: \n");
//IntSelecttionSort(charSort);
TextIO.putln(Arrays.toString(charSort));
TextIO.put("Enter: "); RemoveShift (charSort, TextIO.getInt());
}
public static void RemoveShift (int[] move, int p){
for(int i = 0; i<move.length; i++){
TextIO.put(i+", ");
}
TextIO.putln();
for(int i = p; i<move.length-1; i++){
move[i]=move[i+1];
}
move[move.length-1]=null; // null seems not to work here
TextIO.putln(Arrays.toString(move));
}
int is a primitive, and can't be assigned the value null.
If you want to use null here, you can use the wrapper class Integer instead:
public static void RemoveShift (Integer[] move, int p){
Because of autoboxing, you can even initialize your array in the same way:
Integer[] charSort = new Integer[] {12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11};
As #JBNizet points out, a nice alternative if you want to modify an array of Integer is to use an ArrayList instead. That can make your life much easier.

How to use java.util.Arrays

I'm trying to use the java.util.Arrays class in JavaSE 6 but not sure how i would implement it? on an array that I have generated?
before the start of the class i have
import java.util.Arrays
Java Arrays
To declare an array of integers, you start with:
int[] myArray;
To instantiate an array of ten integers, you can try:
myArray = new int[10];
To set values in that array, try:
myArray[0] = 1; // arrays indices are 0 based in Java
Or at instantiation:
int[] myArray2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
To get values from the array, try:
System.out.println(myArray[0]);
To print all the values in an array, try:
// go from 0 to one less than the array length, based on 0 indexing
for(int i = 0; i < myArray2.length; i++) {
System.out.println(myArray2[i]);
}
For more information, the tutorial from Sun/Oracle will be of great help. You can also check out the Java language specification on Arrays.
Using the Arrays Utility Class
java.util.Arrays contains a bunch of static methods. Static methods belong to the class and do not require an instance of the class in order to be called. Instead they are called with the class name as a prefix.
So you can do things like the following:
// print a string representation of an array
int[] myArray = {1, 2, 3, 4};
System.out.println(Arrays.toString(myArray));
Or
// sort a list
int[] unsorted = {3, 4, 1, 2, 5, 7, 6};
Arrays.sort(unsorted);
Well let's say you have an array
int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9};
And you want to sort it. You do this:
// assumes you imported at the top
Arrays.sort(myArray);
Here's the whole shebang:
import java.util.Arrays;
class ArrayTest {
public static void main(String[] args) {
int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9};
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
And that results in
C:\Documents and Settings\glow\My Documents>java ArrayTest
[1, 2, 3, 4, 6, 8, 9]
C:\Documents and Settings\glow\My Documents>
You have not provided enough information about what you are trying to do. java.util.Arrays only exposes static methods, so you simply pass in your array and whatever other params are necessary for the particular method you are calling. For instance Arrays.fill(myarray,true) would fill a boolean array with the value true.
Here is the javadoc for java.util.Arrays
You can use a static import
import static java.util.Arrays.*;
int[] ints = {3, 4, 1, 2, 5, 7, 6};
sort(ints);
public static void main(String[] args) {
double array[] = {1.1,2.3,5.6,7.5, 12.2, 44.7,4.25, 2.12};
Arrays.sort(array,1,3);
for(int i =0;i <array.length;i++){
System.out.println(array[i]);
}
}
result:
"1.1,2.3,5.6,7.5,12.2,44.7,4.25,2.12"

Categories