Hi I am trying to take two arrays and turn them into one 2 dimensional array. However, I keep getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
Here is my code:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
I am not really sure what the problem is. Sorry if the question is dumb, I am new to coding!
The problem is:
final23 [2][i] = y[i];
Java arrays always start at 0. So final23 only has [0] and [1].
Any array with n elements can go from 0 to n-1.
There is also a second problem with your program. You have this loop in both sum and print methods:
for (int i = 0; i < final23[i].length; i++)
In sum method it should be
for (int i = 0; i < final23[0].length; i++)
And in print method
for (int i = 0; i < final23.length; i++)
Otherwise you'll get ArrayIndexOutOfBoundsException again.
Note that the program works correctly only if both input arrays have the same length. This might be ok for your purposes, but keep that in mind.
Try
for (int i = 0; i < final23[i].length; i++)
{
final23 [0][i] = x[i];
final23 [1][i] = y[i];
}
Remember, all arrays are 0 based, even n-dimensional ones.
Related
Given an array/list 'ARR' of integers and a position ‘M’. You have to reverse the array after that position. You do not need to print anything, it has already been taken care of. Just implement the given function.
This is my problem statement. The following is the code I tried implementing.
public class Solution
{
public static void reverseArray(ArrayList<Integer> arr, int m)
{
int i=0,p=1;
int n=arr.size();
ArrayList<Integer> reverseArray=new ArrayList<Integer>();
for(int j=0;j<n;j++){
reverseArray.add(0);
}
for(;i<=m;i++){
reverseArray.set(i, arr.get(i));
}
for(;i<n;i++){
reverseArray.set(i,arr.get(n-p));
}
for(int j=0;j<n;j++){
arr.set(i,reverseArray.get(i));
}
}
}
I'm getting runtime error as
Exception in thread main java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Solution.reverseArray(Solution.java:21)
at Runner.executeAndPrintOutput(Runner.java:50)
at Runner.main(Runner.java:61)
Content of arr={1, 2, 3, 4, 5, 6}
First of all, your problem is that in the last loop you are using i, instead of j. Second, your logic seems faulty to me. Here is a simple solution I've programmed -
public static void reverseArray(ArrayList<Integer> arr, int m) {
int i = 0, p = 1;
int n = arr.size();
ArrayList<Integer> reverseArray = new ArrayList<Integer>();
for (i = m; i < n; i++){
reverseArray.add(arr.get(n - i - 1 + m));
}
for (i = m; i < n; i++){
arr.set(i, reverseArray.get(i - m));
}
}
May be something like this? remove the print statements before submitting.
private void reverseArray(List<Integer> src, int pos) {
int j = 0;
Integer[] srcArr = new Integer[src.size()];
Integer[] tarArr = new Integer[src.size()];
src.toArray(srcArr);
src.toArray(tarArr);
for(int i=pos; i<srcArr.length; i++) {
j++;
int tarIndex = srcArr.length-j;
int tarEle = srcArr[tarIndex];
tarArr[i] = tarEle;
}
for(int i = 0; i<tarArr.length; i++) {
System.out.print(tarArr[i] + " ");
}
}
Want to write the diagonal of an 2-dimensional array (n*n Matrix) into an one-dimensional array.
1 2 3
4 5 6 => 1 5 9
7 8 9
public int[] getDiagonalFromArray(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array[0].length];
int k=0;
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
for (int l = 0; l < two_d_array[0].length; l++) {
diagonal_array[k]=two_d_array[i][j];} //HERE SHOULD BE THE ERROR... HOW DO I CYCLE THROUGH THE 1dim "diagonal_array"?
}
}
return diagonal_array;
}
This method delivers wrong values.
This method of mine works, but just Prints the diagonale, instead of putting it into an 1dim array.
public void getDiagonal(int[][] two_d_array){
//int[] diagonal_array = new int[two_d_array[0].length];
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
if (i==j) System.out.print(two_d_array[i][j]+" ");
}
}
}
Where is the logical difference? I tried the if-clause on the first method, but it raises the "outofbound"-Exception.
Thanks in advance.
Why do you need more than one loop?
for (int i = 0; i < two_d_array[0].length; i++) {
diagonal_array[i]=two_d_array[i][i];
}
Seems to be enough to me.
If your matrix has the same width and height, this is a solution:
public int[] getDiagonal(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array.length];
for (int i = 0; i < two_d_array.length; i++) {
diagonal_array[i] = two_d_array[i][i];
}
return diagonal_array;
Here, I consider principal diagonal elements to be the set of elements , where n & m are the number of rows and the number of columns (per row?) respectively.
Thus, the number of diagonal elements is never greater than min(numOfRows, numOfColumns).
And so, you can always try:
public int[] getDiagonalFromArray(int[][] 2DArray){
int[] diagonalArray = new int[Math.min(2DArray.length, 2DArray[0].length]);
int k=0;
for (int i = 0; i < 2DArray.length && k < diagonalArray.l length; ++i) {
for (int j = 0; j < 2DArray[i].length && k < diagonalArray.l length; ++j) {
if (i == j) {
diagonalArray[k++]=2DArray[i][j];
}
}
}
return diagonalArray;
}
Threw in some bounds checks for good measure.
Your input matrix must at be at least rectangular (square makes most sense), otherwise, the code will behave unreliably.
This is the same as #Andreas' answer, but I sacrifice performance and brevity here for the sake of understanding.
This algorithm given to us in class:
I am having trouble in my attempts to determine the output when the input is an array A[60,35,81,98,14,47].
I wanted to get used to the pseudocode syntax, so I tried to convert this to Java syntax, but the resulting program won't show a result. This is my converted code:
public class Driver
{
public static void main(String[] args)
{
int[] test = {60, 35, 81, 98, 14, 47};
int[] converse = new int[6];
converse = countSort(test);
for(int i : converse)
{
System.out.println(converse[i]);
}
}
public static int[] countSort(int[] a)
{
int[] s = new int[6];
int[] count = new int[6];
int n = a.length + 1;
for(int i = 0; i < (n-1);)
{
count[i] = 0;
}
for(int i = 0; i < (n-2);)
{
for(int j = (i+1); i < (n-1);)
{
if(a[i] < a[j])
{
count[j] = count[j]+1;//What
}
else
{
count[i] = count[i]+1;
}
}
}
for (int i = 0; i < (n-1);)
{
s[count[i]] = a[i];
}
return s;
}
}
int[] test = {60,35,81,98,14,47}; is never used.
Did you mean to pass test into countSort? and also do something with it's result.
While I haven't looked at the algorithm really, there is something else wrong here:
int n = a.length + 1;
for (int i = 0; i < (n - 1);) {
count[i] = 0;
}
This will loop indefinatetly. i never incerements.
Your array test is never used.
In your for loops, i never gets incremented. It will loop infinetely.
Instead of n = a.length+1; just use n = a.length. it makes your code easier to read. You then also have to check all your loops.
When you are running the code with a testset larger or less than 6 integer values your code wont run correctly or even fail with an ArrayOutOfBounds Exception, as you allocate the arrays s and count for only 6 values.
Try int[] count = new int[a.length]; instead of int[] count = new int[a.length];. The same for s.
I am trying to concatenate two two-dimensional arrays of different sizes. I have no idea why my method doesn't work. Java tells me, when I mouse over the "return xx": "Type mismatch: cannot convert from int[][] to int[]". When I mouse over "concatenateArr2d..." I get: "Illegal modifier for parameter concatenateArr2d: only final is permitted".
I don't understand why I am getting this error.
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int[][] xx = new int[t.length + s.length][];
for(i = 0; i < xx.length; i++)
{
xx[i] = new int[t[i].length + s[i].length];
}
return xx;
}
I still have to do the code to fill the entries but that should not be a problem.
Any help please? Thank you.
It looks to me that the code before the bit you pasted does not have aligned braces. You're probably inside a method when you try to declare this method.
public class HelloWorld{
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int jLength=0;
// The below line of code is to determine second dimension size of new array
jLength=Math.max(s[0].length, t[0].length);
int sIterate=0;
//new array created using size of first+second array for First dimension and maximum size for second dimension
int[][] xx = new int[t.length + s.length][jLength];
//first array copy
for(int i = 0; i < t.length; i++)
{
for(int j = 0; j < t[0].length; j++)
{
xx[i][j] =t[i][j];
}
}
//second array copy
for(int i = t.length; i < xx.length; i++)
{
for(int j = 0; j < s[0].length; j++)
{
xx[i][j] =s[sIterate][j];
}
sIterate++;
}
return xx;
}
public static void main(String []args){
int a[][]={{1,2},{2,3},{1,1}};
int b[][]={{1,2,3},{2,3,4}};
int c[][]=HelloWorld.concatenateArr2d(a,b);
//Output iteration
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c[0].length; j++)
{
System.out.print(c[i][j]);
}
System.out.println();
}
}
}
note : The blanks filled by 'primitive type default value' like, for int its 0.
Output :
120
230
110
123
234
I'm trying to create a program to create an array of the numbers 1 through 100 and then randomize them. So far I have this, but don't know what to do next:
public class Random100Array
{
public static void main(String args[])
{
{
int[] nums = new int[100];
char current;
int a;
for (int i = 0; i <= nums.length; i++) {
nums[i] = i + 1;
}
for (int i1 = 0; i1 <=nums.length; i1++) {
double random = (Math.random() * 100) + 1;
}
}
}
}
Also, THIS ISN'T HOMEWORK. I am a student and I'm currently on winter break. This program gives me this output for some reason. What am I doing wrong?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Random100Array.main(Random100Array.java:11)
Use < instead of <= in your for loops.
Firstly, you should take care of your for-loops conditions as mentioned in other answers.
Then, for shuffling your input array, you can use this code:
import java.util.Random;
public class Program {
public static void main(String[] args)
{
int[] nums = new int[100];
for(int i = 0; i < nums.length; ++i)
{
nums[i] = i + 1;
}
Random generator = new Random();
for(int i = 0; i < nums.length; ++i)
{
int j = generator.nextInt(nums.length - i);
int tmp = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = nums[j];
nums[j] = tmp;
}
}
}
Initializing an array with the length of 100 means, you have indices ranging from 0 to 99, so you won't have index 100, thats why you receive this exception. nums.length will be 100 (since you initialize the length with 100. Basically your for-loop is ranging from 0 to 100 (which are 101 nums) this is out of bound.
Use < instead of <= inside the for loops
for shuffeling the array, try something like this:
https://stackoverflow.com/a/1520212/995320
You need to use < and not <=
Also, you can use a try catch to escape the exception, but this would not be considered good practice