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

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.

Related

Index of number(s) in list in JAVA

I need to have a program that asks the user for a number, and reports that number's index in the list. If the number is not found, the program should not print anything.
Example:
Sample Output:
1
2
3
3
4
Search for? 3
3 is at index 2
3 is at index 3
This is what I have written but the put is looping multiple times. Can you suggest fixing it?
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
break;
}
list.add(input);
}
System.out.println("Search for? ");
int src = scanner.nextInt();
int ind = 0;
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = list.indexOf(src);
}
System.out.println(src + " is at index " + ind);
}
}
}
EDIT
Input: 1 2 3 3 4 -1
Search for? 3 Output: 3 is at index 0 3 is at index 0 3 is at index 2 3 is at index 2 3 is at index 2 ///So it must be only one sentence for each index. Even if I put after "for" loop, it only output the first if index.
I can see a single problem in your code, that is, you print everything, not only the matches. To solve that you need to put your System.out.println into the if, like this:
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = i;
System.out.println(src + " is at index " + ind);
}
}
Let me know if anything else was wrong.

Why for loop in java wont make any difference if its present or not

In my program in certain function i have to fill 3x3 square of 9x9 array. At first glance it seems to be as trivial as it sounds but somehow one for() loop is not working properly. I asked two friends of mine and checked the code several times but still cant find any mistake everything seems to be working just fine if we do not count one for function. I tried to change it to other loop and it also didnt work. Below i give you my code and the outcome.I tried to serch the web for similar problem but also couldnt find one. Thank you in advance!
Code:
import java.util.Random;
public class ttabela
{
public static void main(String[] args) {
boolean bylo[] = new boolean[10];
int tabela[][] = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tabela[i][j] = 0;
}
}
wypelnianiePrzekatnych(bylo, tabela,0,2);
clear(bylo);
System.out.println("");
for(int i=0;i<3;i++) {
for (int j = 0; j < 3; j++) {
System.out.print(tabela[i][j]+" ");
}
System.out.println();
}
System.out.println("");
for(int x=0;x<9;x++)
System.out.print(tabela[0][x]+" ");
}
static int RandomBeetween ( int min, int max)
{
Random random = new Random();
int a1 = random.nextInt(max - min);
int a2 = a1 + min;
return a2;
}
static void wypelnianiePrzekatnych(boolean[] bylo, int[][] tabela,int i,int j){//i=0 j=2
int a = i,b=i ;
for (;a < (j+1);a++) { //This one doesnt make any difference
for (;b < (j+1); b++) {
System.out.println("p "+a+" "+b+" k");
tabela[a][b] = RandomBeetween(1, 10);
System.out.println(tabela[a][b]);
if (bylo[tabela[a][b]] == true) {
do {
tabela[a][b] = RandomBeetween(1, 10);
}while (bylo[tabela[a][b]] == true);
bylo[tabela[a][b]] = true;
System.out.println(tabela[a][b]);
}
else {
if (bylo[tabela[a][b]] == false)
bylo[tabela[a][b]] = true;
System.out.println(tabela[a][b]);
}
}
}
}
static void clear(boolean[] bylo)
{
for(int h=0;h<10;h++)
bylo[h]=false;
}
/*public static void wypelnianieReszty()
{
}*/
}
Outcome:
p 0 0 k
7
7
p 0 1 k
8
8
p 0 2 k
3
3
7 8 3
0 0 0
0 0 0
7 8 3 0 0 0 0 0 0
The problem is that your inner for loop will only execute once, so the outer loop has nothing to run after the first iteration.
I'll explain in more detail.
You start with:
int a = i,b=i ;
Let's say we passed in (..., 0, 2) as you have done. So a = 0, b = 0.
The outer for loop will run just fine exactly as expected - the code will run until a > (j+1) and there's nothing wrong here.
The problem is actually with your second for loop:
for (;b < (j+1); b++) {
For the first iteration, this will run as expected. But any time after that, it will never run - because you have already incremented b, such that b == (j+1).
I believe there is a fairly simple solution, assuming I've interpreted your requirements correctly:
int a = i;
int b;
for (;a < (j+1);a++) { //This one doesnt make any difference
b = i
for (;b < (j+1); b++) {
This works because it resets the value of b before each iteration of the for loop, so it won't halt immediately.
I hope this helps! Feel free to ask any questions in the comments.

Method returns the number of times that three or more consecutive keys appear

For the question that currently has me stumped, I'm supposed to write a static method named countTriples that will take any int array as a parameter, and an integer key, and return the number of times that three or more consecutive keys appear. A sequence of more than three keys still counts as one triple.
pseudocode example: countTriples([1 3 3 3 0 3 3 1 3 3 3 8], 3) => 2
pseudocode example: countTriples([1 7 7 7 0 7 7 7 7 1 7 7 7 7 7 8], 7) => 3
pseudocode example: countTriples([1 14 14 4 1 14], 14) => 0
Here's what I have so far, it works for some cases, but not for ones such as: {1,2,1,1,1,5,6,7,8,1,1,1,1}
import java.util.*;
public class Sample {
public static int countTriples(int[] data, int key) {
int count = 0;
int c= 0;
for (int i = 0; i < data.length-1; i++) {
if (data[i] == key) {
c++;
if (c >= 3) {
count++;
c = 0;
}
}
else {
count = 0;
}
}
System.out.println(count);
return count;
}
public static void main(String[] args) {
int[] arr = {1,2,1,1,1,5,6,7,8,1,1,1,1};
countTriples(arr, 1);//currently returns 1, 2 expected
}
}
Any help is appreciated
We create an initial loop and loop through all values until we find one that matches the key. When we do we create another loop to start at the next index until we find one that doesn't match, or until we hit the end (this is important). Once we hit a non-key value we check if the offset in the current for-loop is 3 or greater than the initial for-loop. If so, we increase count and offset the initial loop by the amount we looped in the second loop to ensure no duplicates.
public static int countTriples(int[] data, int key) {
int count = 0;
for (int index = 0; index < data.length; index++) {
int valueAtIndex = data[index];
if (valueAtIndex != key) {
continue;
}
for (int offset = index + 1; offset < data.length; offset++) {
int valueAtOffset = data[offset];
if (valueAtOffset != valueAtIndex || offset == data.length - 1) {
int indexOffset = offset - index;
if (indexOffset >= 3) {
index += indexOffset - 1;
count++;
}
break;
}
}
}
return count;
}

How would I test a random two-dimensional array for consecutive even integers?

I am writing this program in which a user enters the dimensions for a table, a table is then created with those dimensions and the elements within it are determined from a random generator with integers from 0 to 9. Then, what I need to do is create a loop that will determine if there are four consecutive even integers in the table.
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.
Here is what I have done so far:
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();
}
}
}
I know it isn't much, I have only created the two scanners and the table. I don't know how to go about creating the loop to determine the four consecutive even integers though. As I think about it, I am wondering if the way to do this is to create a nested loop that examines the first row and then the first column, then determine if either of that row or column contains the same integer four times. Then repeat that based upon the dimensions of the user input. I'm not sure though...
I know that this is the primary idea for this would be:
if there is x number that repeats consecutively four times in a row, then return true; else false
if there is x number that repeats consecutively four times in a column, then return true; else false
if there is x number that repeats consecutively four times in surrounding corner, then return true; else false.
Now, that is just pseudo-code to refer back to, but I'm seriously stumped on how I would do this and would appreciate some input from others.
You could use a nested for loop for to check in each dimension, and then, and then swap the loop counters to check the opposite.
I haven't tested this, but I think it should work:
import java.util.*;
public class FourConsecutiveNumbers {
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;
}
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;
}
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 =randomTable.length; t>2; 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;
}
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("There are 4 in a row, in some way");
}
else{
System.out.println("No luck");
}
}}
You could try iterating through the items in the table. For each one, if there is a matching number adjacent to it, there is the beginning of four consecutive even integers. From there, you just have to keep searcghing in the same direction.

Printing an array on a certain line

I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers. Also who do i Enter numbers into an array without defining how many numbers will be entered?
import java.util.Scanner;
public class NumberArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many grades do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " grades now.");
for (int grades = 0 ; grades < array.length; grades++ )
{
array[grades] = input.nextInt();
}
System.out.println("These are the grades you have entered.");
printArray(array);
}
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " \t");
}
}
}
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers.
From this question, it seems to indicate that you want the output to look like this:
1 2 3 4 5 6
7 8 9 ... n
This can be achieved quite simply.
Option 1 - The classic If statement
for(int x = 0; x < array.length; x++) {
System.out.print(array[x]);
if(x == 5) {
// 5 because we're counting from 0!
System.out.println();
}
}
Option 2 - Using the Ternary operator to keep it on one line
NOTE: This is more or less the same. It's just nice to be complete in these sorts of answers.
for(int x = 0; x < array.length; x++) {
System.out.print(array[x] + x == 5? "\n":"");
}
Edit
If you meant that you want 6 items on each line, like so:
1 2 3 4 5 6
7 8 9 10 11 12
...
Then you can use the % (The modulus operator) to print out a new line on every output. This is actually quite easy to change, but you'll need to make sure that you're checking the value before you're outputting the content. This can be shown in this IDEOne.
Use modulus operator (%) to break to a new line line:
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
if(i % 6 == 0) // if you don't want the initial newline, check for i > 0
System.out.println()
System.out.print(arr[i] + " \t");
}
}
you can also use printf() method to format the line; which is probably better:
System.out.printf("%5d", arr[i]);
The reason why this is better, is because you can easily format the output to a specific justification, column width, etc., which will make your output look better.

Categories