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);
}
Related
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;
}
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);
}
}
I am having difficulty in making the logic for my scenario which i m considering an array of arrays more specifically said as 2D array.i want to find the maximum value in 2D arrays i do not want to call it in main method.i am making the array as annonymous and calling the function of max from it via static data members.the code is as follows.do let me know the logic to find the greatest no in 2D array as i m finding it difficult to which value to compare with the array.the code is as follows:-
class Max2DArray
{
static int i;
static int j;
static int large;//largest number
int max(int x[][])
{
for(int i=0;i<x.length;i++)
{
for(j=0;j<x[i].length;i++)
{
if(x[i][j]<=???)//what should be the comparison here.
{
??//what should be done here??
}
}
}
return large
}
public static void main(String... s)
{
Max2DArray m1 = new Max2DArray();
int t = m1.max(new int[][]{{20,10,5},
{5,7,6},
{23,31,16}});
System.out.println("the largest number is = "+t);
}
}
I am not going to solve it to you but here is an algorithm
Have a local variable max
assign max to the first value of the array
iterate through the array and change the value of max whenever you find a value greater that the current value of max.
return max
Try this:
int max(int x[][]){
// Initialize the value to the lowest value
int large = Integer.MIN_VALUE;
for(int i = 0; i < x.length; i++) {
for(j = 0; j < x[i].length; j++) {
// Check if the current value is greater than large
if(x[i][j] > large) {
// It is greater so we keep the new value
large = x[i][j];
}
}
}
return large;
}
Using java 8, it could simply be:
int max(int x[][]){
return Arrays.stream(x).flatMapToInt(IntStream::of).max().getAsInt();
}
A Java 8 one-liner, instead of your for loop:
Arrays.stream(x).flatMapToInt(arr2 -> Arrays.stream(arr2)).max().getAsInt();
I saw the below code in a book. I know that the void method cannot return a value. when I ran the code, the compiler could not print the modified array, while in the book, the values are shown. How can I fix the code to print the modified array?
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println("The values of original array are:");
for(int value: array)
{
System.out.print(value + "\t");
}
modifyArray(array);
System.out.println("The values after modified array are:");
for (int value:array)
{
System.out.print(value + "\t");
}
}
public static void modifyArray(int[] b)
{
for (int counter=0; counter<=b.length; counter++)
{
b[counter] *=2;
}
}
If I am not mistaken, you should be getting an ArrayIndexOutOfBoundsException for your modifyArray() method. change the for loop in the method to
for (int counter=0; counter<b.length; counter++) // use < not <=
{
b[counter] *=2;
}
for (int counter=0; counter<=b.length; counter++)
This code runs for 6 times thus trying to access the 6th element of your array which doesn't exist. It must be ArrayIndexOutOfBoundsException error.
Change above line to:
for(int counter = 0; counter<b.length; counter++)
This will work!
The code actually works but there is an error in the method for loop that cause a IndexOutOfBound Exception this is the correct version.
public static void modifyArray(int[] b)
{
for (int counter=0; counter<b.length; counter++)
{
b[counter] *=2;
}
}
The method returns void but you can read the modify values inside the array because you are passing as method argument the reference of the array not a copy of the array. this is a very basic concept of the Java Language you should start reading
Passing Information to a Method or a Constructor.
How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);