This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
import java.util.*;
class Example{
public static int[] reverse(int[]ar){
for (int i = 0; i < (ar.length); i++)
{
ar[i]=ar[(ar.length-i-1)];
}
return ar;
}
public static void main(String args[]){
int[] xr={10,20,30,40,50};
System.out.println(Arrays.toString(xr));
int[]y=xr;
int[]z=reverse(xr);
System.out.println(Arrays.toString(z));
}
}
This code output get: [50,40,30,40,50].
But I want to print the reverse of the given Array.
And I want to know how this output([50,40,30,40,50]) generated
When i=0
ar[i]=ar[(ar.length-i-1)]
assigns the last element of the array to the first index of the array. Thus the original first element of the array is overwritten before you have a chance to assign it to the last index.
This happens for all the indices of the first half of the array.
If you want to reverse the array in place, you need some temp variable, and you should make a swap in each iteration:
public static int[] reverse(int[]ar)
{
for (int i = 0; i < ar.length / 2; i++) {
int temp = ar[i];
ar[i] = ar[(ar.length-i-1)];
ar[(ar.length-i-1)] = temp;
}
return ar;
}
Related
This question already has answers here:
How to create a sub array from another array in Java?
(8 answers)
Closed 3 years ago.
I am trying to print out the 'middle' of the 2D array (a). For example, for given arrays in my code, I would like to print:
[3,4,5,6]
[4,5,6,7]
However I was only able to print out the 'middle' values. I would like to modify the 2D array (n) according to the explanation and print it instead.
How would I go about doing this?
Here is my code:
public static int[][] inner (int[][] a) {
int rowL = a.length - 1;
int colL = a[1].length -1;
for (int row = 1; row < rowL; row++) {
for (int col = 1; col < colL ; col++) {
System.out.print(a[row][col]);
}
System.out.println();
}
return a;
}
public static void main(String[] args) {
int [][] a = { {1,2,3,4,5,6},
{2,3,4,5,6,7},
{3,4,5,6,7,8},
{4,5,6,7,8,9} };
for (int[] row : a) {
System.out.println(Arrays.toString(row));
}
System.out.println();
for ( int[] row : inner(a) ) {
System.out.println(Arrays.toString(row));
}
}
First, you need to create a new empty array with the correct size. Then you fill in the values of the new array instead of printing them.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am trying to find the max value of a 2D array in java.
import java.util.*;
public class ikiBoyutlu {
public static void ikiBoyut(int[][]a){
int eb= a[0][0];
for(int i=0;i<a.length;i++){
for(int j=0; j<(a[0].length);j++){
if(a[i][j]>eb){
eb=a[i][j];
}
}
}
System.out.println("The max value of array= "+ eb);
}
public static void main(String[] args){
int a[][] ={{2,5,7,0,-6,28,43},{-96,45,3,21}};
ikiBoyut(a);
}
}
But I get index out of range error. I wonder why?
Thanks!
You're iterating over different nested arrays, while invariably watching i < a[0].
Your inner loop should be declared this way, instead:
for(int j=0; j<(a[i].length);j++)
and in your example the second inner array is smaller than the first. so when iterating through the second with the length of the first, it will definitely get out of the bounds ...
You have a two dimensional array, which is basically an array of arrays.
Your two two dimensional array effectively contains two arrays with different lengths.
Your second loop has the condition of
j<(a[0].length)
when it should be
j<(a[i].length)
Use the length of each array element.
You are testing the inner loop against a[0].length which is the length of the first array in your jagged multidimensional array (and longer than the second). Instead, use a[i].length - and you might also initialize eb with Integer.MIN_VALUE and use Math.max(int, int) instead of coding your own test. Like,
public static void ikiBoyut(int[][] a) {
int eb = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
eb = Math.max(eb, a[i][j]);
}
}
System.out.println("The max value of array= " + eb);
}
This is also a place where you could potentially eliminate errors by using a for-each loop. For example,
public static void ikiBoyut(int[][] a) {
int eb = Integer.MIN_VALUE;
for (int[] arr : a) {
for (int i : arr) {
eb = Math.max(eb, i);
}
}
System.out.println("The max value of array= " + eb);
}
And, in Java 8+, we can use lambdas to shorten it significantly. Like,
public static void ikiBoyut(int[][] a) {
int eb = Stream.of(a).flatMapToInt(IntStream::of).max().orElse(Integer.MIN_VALUE);
System.out.println("The max value of array= " + eb);
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I want to shift elements in an array to the right by 1. The last element should go to position 0. So far, I only have the shifting to the right part done, I want to see if this is the right but when I press run, nothing shows up in the console. I know I have to put System.out.println(); in the main but I don't know what to call with the print command. Here is my code.
I tried putting in System.out.println(rotate({1,2,3,4})); into main but I get an error...
public class Rotate {
static void rotate(int[] A) {
int arrayLength = A.length;
for(int i = 0; i <= arrayLength-1; i++){
A[i] = A[i+1];
}
}
public static void main(String[] args){
}
}
You need to make a call to a function that can print, for example System.out.println(). Now there are some other issues with your code and you'll need to make some changes (there is more than one way to do this). One way would be to return an array from your rotate function, and then print the arrays that is returned.
static int[] rotate(int[] A) {
int arrayLength = A.length;
for(int i = 0; i <= arrayLength-1; i++){
A[i] = A[i+1];
}
return A;
}
We can call this now from our main method, and print each element. If you just call the System.out.println()method and pass it an array, it will print the Hashcodefor this object. This is not that usefull for printing information of an array. So instead, you can write a loop and print each element in the array.
public static void main (String[] args)
{
int[] x = {1,2,3,4};
int[] y = (rotate(x));
System.out.println(y) // prints the hash, not what you want..
for(int i = 0; i < y.length(); i++){
System.out.println(y[i]);
}
}
Instead of printing each element of the array seperately, you could also print the entire array using System.out.println(Arrays.toString(y));.
You'll still get an error now
This is because your rotate method is not implemented correctly. But that is beyond the scope of this question I suppose.
To verify that this is actually working, you could try to print the array before applying rotateto it.
int[] x = {1,2,3,4};
for(int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
// or alternative
System.out.println(Arrays.toString(x));
To solve rotate and print problem (and if you don't want to return array):
static void rotate(int[] A) {
int arrayLength = A.length;
int t = A[arrayLength-1];
for (int i = arrayLength - 1; i > 0; i--) {
A[i] = A[i-1];
}
A[0] = t;
for (int i : A) {
System.out.println(i);
}
}
This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 7 years ago.
I have a basic java question - I have an array and I need to do a multiplication of all the elements, so for input:
1 2 3
The output will be:
1 2 3
2 4 8
3 6 9
How can I print the 2d array from the main ?
PS - I want the method just to return the new 2d array, without printing it ( I know I can do it without the method and and print mat[i][j] within the nested loop)
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println(matrix(array));
}
public static int[][] matrix(int[] array){
int[][] mat = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
mat[i][j] = array[i] * array[j];
}
}
return mat;
}
}
You have to print all the individual elements of the array, because if you just try to print an array, it will print all kinds of other stuff you might not want to see. So you cherry pick out what you want, and format it a little. In the below code you have each element printed, seperated on a space until it reaches a new row, where it then jumps to a new line.
int[][] matrixArray = matrix(array);
for(int i = 0, i < matrixArray.length; i++) {
for(int j = 0; j < matrixArray[0].length; j++) {
System.out.print(matrixArray[i][j] + " ");
}
System.out.println();
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
I'm trying to create a program that removes a given character from an array and then prints out the new array and whenever I print it out I get weird results like [I#120acab
public static int[] removeVal(int[] numArray, int val)
{
int purge = 0;
int keep = 1;
int arrayVal = 0;
for (int item : numArray)
{
if(item == val)
purge = purge + 1;
else
keep = keep + 1;
}
int[] newArray = new int[keep];
for (int taco : numArray)
{
if(taco != val)
newArray[arrayVal] = taco;
arrayVal = arrayVal + 1;
}
return newArray;
}
You should use Arrays.toString to print the array. This will show the individual elements of the array.
The default toString implementation of Object class returns what you see.