ArrayIndexOutOfBounds. Java Spiral Program - java

I keep getting the error ArrayIndexOutOfBounds: 4 on line 21. The line is Spiral[VIndx][HIndx]=number. This program is supposed to create a spiral of numbers when given a certain dimension. For example, if given the dimension 3, a 3x3 2d array that spirals numbers. Here's what the spiral should be:
7 8 9
6 1 2
5 4 3
Why aren't my loops working?
import java.util.*;import java.io.*;
public class Spiral{
public static void Spiral(int dimensions, int [][] Spiral)
{
int endNumber = (int)Math.pow(dimensions, 2);
int number = 1;
int rightmovement = 1;
int downmovement = 1;
int leftmovement = 2;
int upmovement = 2;
int HIndx = (dimensions-1)/2;
int VIndx = (dimensions-1)/2;
while(number<=endNumber)
{
for(int i = 0;i<=rightmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
HIndx++;
if(number==endNumber)break;
}
rightmovement++;
for(int i = 0;i<=downmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
VIndx++;
if(number==endNumber)break;
}
downmovement++;
for(int i = 1;i<=leftmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
HIndx--;
if(number==endNumber)break;
}
leftmovement++;
for(int i = 1;i<=upmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
VIndx--;
if(number==endNumber)break;
}
upmovement++;
}
}
public static void main(String[]args)throws IOException
{
File file = new File("spiral.txt");
Scanner input = new Scanner(file);
String [] numbers = new String [2];
int i =0;
while (input.hasNextLine())
{
String line = input.nextLine();
numbers[i]=line;
i++;
}
int dimensions = 0;
input.close();
int [][] Spiral = new int [dimensions][dimensions];
dimensions = Integer.parseInt(numbers[0]);
int range = Integer.parseInt(numbers[1]);
if(dimensions%2==0)
{
dimensions+=1;
}
Spiral(dimensions, Spiral);
for(i = 0; i<dimensions;i++){
for(int j = 0; j<dimensions;j++){
System.out.println(Spiral[i][j]);
}
}
}
}

First, your loop condition should use < rather than <=.
Second, if you think about the spiral you'll realize that you always end with a right movement. You hit the break at the first time you have
if(number==endNumber)break;
but this doesn't exit you out of the while loop - this only leaves the for loop. So then you go into the down movement for loop and get the index out of bounds exception.
Third, you need to first enter the center number before the loop.
Additionally, rightmovement, leftmovement, ... should all be increased by 2 each time. The reason for this is easier to see in a larger grid.
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
Notice the first right movement writes 2, then the next one writes 8 9 10, and the last one writes 22 23 24 25 and would have written 26 if you were to continue.
To fix the issue with break not leaving the while loop, just change it into a return statement.

Related

How do I swap columns with a specific indexes in java 2d arrays?

So I've been trying to solve following problem:
Given a two-dimensional array (matrix) and the two numbers: i and j. Swap the columns with indexes i and j within the matrix.
Input contains matrix dimensions n and m, not exceeding 100, then the elements of the matrix, then the indexes i and j.
Sample Input 1:
3 4
11 12 13 14
21 22 23 24
31 32 33 34
0 1
Sample Output 1:
12 11 13 14
22 21 23 24
32 31 33 34
In order to solve it, I wrote following code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int tables = scanner.nextInt();
int[][] matrix = new int[rows][tables];
int i = scanner.nextInt();
int j = scanner.nextInt();
for (int w = 0; w < rows; w++){
int temp = matrix[w][i];
matrix[w][i] = matrix[w][j];
matrix[w][j] = temp;
}
System.out.print(matrix);
}
}
And the error is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 4 at Main.main(Main.java:15).
What might be the problem and solution to it?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 4 at Main.main(Main.java:15).
Above error is because you are directly reading values into i and j but you forgot setting the values inside the matrix[][] as said by vince and jim in the comments.
Use loop to set the values
for(int k=0;k<rows;k++){
for(int l=0;l<cols;l++){
matrix[k][l]=scanner.nextInt();
}
}
and then loop through rows to swap values
Here goes the code
Live: https://onlinegdb.com/rJJ-kMTUL
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] matrix = new int[rows][cols];
for(int k=0;k<rows;k++){
for(int l=0;l<cols;l++){
matrix[k][l]=scanner.nextInt();
}
}
int i = scanner.nextInt();
int j = scanner.nextInt();
for(int k=0;k<rows;k++){
int temp = matrix[k][i];
matrix[k][i] = matrix[k][j];
matrix[k][j]=temp;
}
for(int k=0;k<rows;k++){
for(int l=0;l<cols;l++){
System.out.print( matrix[k][l]+" ");
}
System.out.println();
}
}
}

Java Exception: Array indexes out of bounds

I was given a lab assignment where we were asked to fill an array of size 50. The first 25 elements had random distinct elements, and the remaining have to be each 26 . All we have to do is print the repeating element,which obviously is 26, using the Las Vegas Algorithm .
I wrote the program and since it's my first time at Java , I am stuck with an exception of Array indexes out of bounds.
I am also sure that there is nothing wrong with the algorithm, and please note that I first created a list and then converted it to array of Integer type.
Hoping for a helping hand.
The code is as follows :-
public class NewClass {
static Random randomGenerator = new Random();
public static void lasveg(Integer a[],int n)
{
int i,j;
boolean chk= true;
while(chk)
{
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
if((i!=j)&&(a[i].equals(a[j])))
System.out.println("The repeated element is : " + i);
}
}
public static void main(String[] args)
{
int i ;
Integer[] arr = new Integer[50] ; //used the Integer wrapper class instead of primitive int
ArrayList list = new ArrayList(50);
for (i=1; i<26; i++)
{
list.add(i) ;
}
Collections.shuffle(list);
for(i=26 ; i<51 ; i++)
{
list.add(26) ;
}
list.toArray(arr) ;
for(i=0 ; i<50 ; i++)
{
System.out.print(arr[i] + " ");
}
lasveg(arr,50);
}
}
The code has several issues:
randomGenerator.nextInt() could return negative numbers and you
can't use negative numbers as index for an array.
if you use % n+1 then you could get an index bigger than 49, which
should be the highest index in an array of length 50.
the third thing is that you have a endless loop, because you never
end the while(true)
If you change all that then your code could look like that:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class NewClass {
static Random randomGenerator = new Random();
public static void lasveg(Integer a[], int n) {
int i, j;
boolean chk = true;
while (chk) {
i = Math.abs(randomGenerator.nextInt()) % n ;
j = Math.abs(randomGenerator.nextInt()) % n ;
if ((i != j) && (a[i].equals(a[j]))){
System.out.println("The repeated element is : " + i);
break;
}
}
}
public static void main(String[] args) {
int i;
Integer[] arr = new Integer[50]; // used the Integer wrapper class
// instead of primitive int
ArrayList list = new ArrayList(50);
for (i = 1; i < 26; i++) {
list.add(i);
}
Collections.shuffle(list);
for (i = 26; i < 51; i++) {
list.add(26);
}
list.toArray(arr);
for (i = 0; i < 50; i++) {
System.out.print(arr[i] + " ");
}
lasveg(arr, 50);
}
}
Output:
24 20 19 14 13 16 10 7 22 18 12 15 2 6 3 25 17 8 1 21 4 5 11 23 9 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 The repeated element is : 26
If you call this function with n = 50 and your array a got 50 elements
public static void lasveg(Integer a[],int n)
{
int i,j;
boolean chk= true;
while(chk)
{
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
if((i!=j)&&(a[i].equals(a[j])))
System.out.println("The repeated element is : " + i);
}
}
Whats happen there is if the random number is (50*x)-1 % 50 + 1 you calling a[50] thats throwing an out of range exception.
You aint want to increase the term rand % n then you get a range from 0 to 49.
Your i and j variables are assigned a random number in the segment from 0 to n, including n
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
In Java the index of the last element of array of n elements is n-1, so there is a possibility, that this statement
if((i!=j)&&(a[i].equals(a[j])))
System.out.println("The repeated element is : " + i);
will cause the index out of bound exception.
The problem that you have here it's that you have to notice that arrays starts at position 0.
array[0];
So, when you use your method lasveg you are setting the number 50 and really trying to access to the position 51 where you do a[i] and a[j] here:
if((i!=j)&&(a[i].equals(a[j])))
To fix your problem you will have to do:
lasveg(arr,49);
Another solution it's to avoid the + 1 in your Random. Change this:
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
to this:
i=(randomGenerator.nextInt())%n;
j=(randomGenerator.nextInt())%n;
I expect it will be helpful for you!

Why do I get an "ArrayIndexOutOfBounds" error in this program?

I have written a program in which the user inputs the dimensions of a two-dimensional array, then the computer prints out the table with those dimensions and fills it with random integers from 0 to 9. Then, if there are four consecutive equal integers that appear anywhere in the table, the computer would return "True". If there are no consecutive equal integers in the table, it would return "False". For instance:
2 5 8 7 1
3 2 9 4 7
5 1 2 0 3
8 0 1 2 7
In that table, two appear consecutively, diagonally from the first spot. It can also be like this:
9 5 3 7 0
2 5 7 3 1
8 5 0 2 9
4 5 1 7 5
In this table, five appear vertically down from the second spot.
This is the code of the program:
/*MyName*/
package fourconsecutivenumbers;
import java.util.Random;
import java.util.Scanner;
public class FourConsecutiveNumbers {
public static void main(String[] args) {
Scanner rowDimension = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int firstInput = rowDimension.nextInt();
Scanner columnDimension = new Scanner(System.in);
System.out.print("Enter the number of columns: ");
int secondInput = columnDimension.nextInt();
int[][] randomTable = new int[firstInput][secondInput];
for (int row = 0; row < firstInput; row++) {
for (int column = 0; column < secondInput; column++) {
randomTable[row][column] = (int)(Math.random() * 10 + 0);
System.out.print(randomTable[row][column] + " ");
}
System.out.println();
}
if(check_horizontal(randomTable) || check_vertical(randomTable) || check_diagonal(randomTable)){
System.out.println("True");
}
else {
System.out.println("False");
}
}
public static boolean check_vertical(int[][] randomTable) {
for (int i = 0; i<randomTable.length; i++){
for(int t=0; t<randomTable[0].length-3;t++){
if (randomTable[i][t]==randomTable[i][t+1] && randomTable[i][t+1]==randomTable[i][t+2] && randomTable[i][t+2]==randomTable[i][t+3]){
return true;
}
}
}
return false;
}
public static boolean check_horizontal(int[][] randomTable){
for (int i = 0; i<randomTable.length; i++){
for(int t=0; t<randomTable[0].length-3;t++){
if (randomTable[t][i]==randomTable[t+1][i] && randomTable[t+1][i]==randomTable[t+2][i] && randomTable[t+2][i]==randomTable[t+3][i]){
return true;
}
}
}
return false;
}
public static boolean check_diagonal(int[][] randomTable){
//check down
for (int t =0; t<randomTable.length-3; t++){
for(int i=0; i<randomTable[0].length-3;i++){
if (randomTable[i][t]==randomTable[i+1][t+1] && randomTable[i+1][t+1]==randomTable[i+2][t+2] && randomTable[i+2][t+2]==randomTable[i+3][t+3]){
return true;
}
}
}
//check up
for (int t =0; t<randomTable.length-3; t--){
for(int i=0; i<randomTable[0].length-3;i++){
if (randomTable[t][i]==randomTable[t-1][i+1] && randomTable[t-1][i+1]==randomTable[t-2][i+2] && randomTable[t-2][i+2]==randomTable[t-3][i+3]){
return true;
}
}
}
return false;
}
}
Now the error I get is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at fourconsecutivenumbers.FourConsecutiveNumbers.check_diagonal(FourConsecutiveNumbers.java:70)
at fourconsecutivenumbers.FourConsecutiveNumbers.main(FourConsecutiveNumbers.java:25)
Java Result: 1
I know that it says the error is at line 70 and then at line 25, but I don't know what I did wrong. I am fairly new to programming so I was hoping that a more experienced program can see what I did wrong. Help is much appreciated!
This is the problem:
randomTable[t-1][i+1]
When t is 0, that will be accessing randomTable[-1][i + 1] - which can never be valid. Likewise you later go on to t - 3.
Additionally, your loop is starting at 0 but then going backwards... so even if the first iteration completed, you'd end up with t=-1 for the second iteration.
You probably want the loop declaration to be:
for (int t = randomTable.length; t >= 3; t--)
Or just:
for (int t = 3; t < randomTable.length; t++)
depending on whether you really need t to decrease or not.
Additionally, I'd recommend that you follow Java naming conventions - checkHorizontal instead of check_horizontal etc.

How to change position of the elements in an array

I'm writing a program, that take 10 Integers from a keyboard and list them in an array indexed from 0-9, and reports the position of the lowest number in the array. If the lowest number has any other position than 0, then the program is supposed to switch the position of the lowest number input with the number in the first position in the array:
import java.util.Scanner;
public class q35 {
public static void main(String args[]) {
Scanner tastatur = new Scanner(System.in);
int[] helTall = new int[10];
int input;
int lowest = Integer.MAX_VALUE;
for(int i=0;i<helTall.length;i++) {
System.out.println("Integers? ");
input = tastatur.nextInt();
if (input < lowest) {
lowest = input;
}
helTall[i] = input;
}
for (int i = 0; i < helTall.length; i++) {
helTall[0] = lowest;
System.out.println(helTall[i]);
}
System.out.println("Lowest number is " + lowest);
}
}
The only problem is that instead of changing position with the lowest number with the number at helTall[0], it just completely replaces the first number in the sequence helTall[0] with the lowest Integer, that way if my input is 4 5 63 23 6 -4 7 33 23 99, then the output becomes -4 5 63 23 6 -4 7 33 23 99 (as you can see the first input number is completely erased), but it should have been -4 5 63 23 6 4 7 33 23 99 any tips/advice/solutions? Thanks in advance.
You should keep track of the index of the lowest number (each time you write lowest = input; you should add lowestIndex=i;.
Then helTall[lowestIndex] will be the lowest number.
So you swap helTall[lowestIndex] with helTall[0] instead of just overwriting the value of helTall[0].
I thought it was enough to describe the solution in words, but I guess it wasn't...
int lowest = Integer.MAX_VALUE;
int lowestIndex = 0;
for(int i=0;i<helTall.length;i++){
System.out.println("Integers? ");
input = tastatur.nextInt();
if (input < lowest){
lowest = input;
lowestIndex = i;
}
helTall[i]=input;
}
// swap the numbers
if (lowestIndex > 0) {
int temp = lowest;
helTall[lowestIndex] = helTall[0];
helTall[0] = temp;
}
// display output
for (int i = 0; i < helTall.length; i ++) {
System.out.println(helTall[i]);
}
This part is wrong:
for (int i = 0; i < helTall.length; i ++) {
helTall[0]=lowest;
System.out.println(helTall[i]);
}
First, you do not need to repeatedly (10 times) put lowest into helTall[0]. Let's move that outside first so it's only done once:
helTall[0]=lowest;
for (int i = 0; i < helTall.length; i ++) {
System.out.println(helTall[i]);
}
Next, the line we put outside the loop overwrites the helTall[0] without regard for what is already in there. We need to temporarily save that number in there elsewhere, then overwrite the spot, so that we can use it to overwrite the spot where the lowest number was:
int numberAtLocationZero = helTall[0];
helTall[0]=lowest;
// Now, on this line we need to write helTall[lowestNumberIndex] = numberAtLocationZero;
for (int i = 0; i < helTall.length; i ++) {
System.out.println(helTall[i]);
}
In the above code I wrote a comment. It relies on you either knowing where in the array the lowest number was, or to find it again. If you add a new variable to your code that takes in values called lowestNumberIndex and update that each time you detect a new lowest number, then you're pretty much done if you uncomment my comment.
You need a separate variable to store what is in the bottom of the array before you overwrite it with your new lowest input number.
helTall[0]=lowest;
should be proceeded by
int placeholder = helTall[0]
and followed by
hellTall[i] = placeholder;
This way, you'll end up swapping the two array elements, the first swapped with the lowest. Is this what you're trying to accomplish? This leaves most of the array unsorted.

Need help writing numbers in the Reverse ORDER

I need some help with this assignment I've been given. Not asking anyone to do my work but I'm really honestly stuck on how to even do this.
I'm supposed to write a program that prompts the user to enter 10 numbers and then have it write all the numbers in reverse order.
Example:
Enter 10 Numbers: 23 89 21 55 67 89 99 13 98 78
Reverse Order: 78 98 13 99 89 67 55 21 89 23
So far all I have is how to get the user inputs. If anyone can push me in the right direction, i'd be very grateful!
import java.util.*;
public class ReverseNumbers
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter 10 numbers:");
for (int i = 0; i< values.length; i++)
{
values[i] = keyboard.nextInt();
}
int[] reverseNums;
reverseNums = new int[10];
for (int i = (values.length -1); i>= 0; i--)
{
reverseNums[ reverseNums.length -1 -i ] = values[ i ];
System.out.println( reverseNums[ i ] );
}
}
}
If you dont want to store the reversed values
for (int i = (values.length -1); i>= 0; i--)
{
System.out.println( values[ i ] );
}
Your code looks good for reading inputs into values. Now you can loop over that array in reverse and print the values:
for (int i = 0; i < values.length; i++)
System.out.println(values[values.length - i - 1]);
Think about it, when i == 0 it will print values[9] since 10 - 0 - 1 = 9. At the end, when i == 9 it will print values[0] since 10 - 9 - 1 = 0.
As you can see, there is no need for the extra reverseNums array.
PS: If you want, you can combine int[] values; and values = new int[10]; into a single line: int[] values = new int[10];
Read in the whole line as a string using Scanner.nextLine(), and then split it into an array using String.split(" ");. After this, you can simply iterate from the end of the array going backwards and print the numbers.
If it's not an assignment then why not try using http://commons.apache.org/proper/commons-lang/ library
ArrayUtils.reverse(int[] array)
I think your code is creating the array correctly. You are just printing out the numbers in the original order because your second for-loop is iterating over them backwards. You can see the correct result by adding the statement below after the last loop:
System.out.println(java.util.Arrays.toString(reverseNums));
You can also perform the complete task with only one iteration:
Scanner keyboard = new Scanner(System.in);
int[] reverseNums= new int[10];
System.out.println("Please enter 10 numbers:");
for (int i = 0; i< values.length; i++) {
reverseNums[values.length -1 - i] = keyboard.nextInt();
}
System.out.println(java.util.Arrays.toString(reverseNums));
To reverse it:
for (int i = 0; i < values.length; i++)
reverseNums[values.length - i - 1] = values[i];

Categories