how to avoid arraysoutofbound exception when using || [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have a question when executing following codes:
if(column!=n-1){
if(returnValue[row][column+1] == 0) column++;
else {
row++;
direction = "down";
}
}
else {
row++;
direction = "down";
}
If you see the codes, I need to check whether the column is exceeding the boundary first and then do another checking, which have duplicated codes in the else section. Is there a better way to write this logic?

I will give you an example cause sounds similar to a matrix issue , please focus on for loops cause the main key is there:
// JAVA Code for Boundary elements of a Matrix
class GFG {
public static void printBoundary(int a[][], int m,
int n)
{
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0)
System.out.print(a[i][j] + " ");
else if (i == m - 1)
System.out.print(a[i][j] + " ");
else if (j == 0)
System.out.print(a[i][j] + " ");
else if (j == n - 1)
System.out.print(a[i][j] + " ");
else
System.out.print(" ");
}
System.out.println("");
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
printBoundary(a, 4, 4);
}
}

in order to avoid getting out of bounds, you'd have to check if row & column are within the boundaries of the array. I do not expect either value to go below 0 as there is no decrement if your code, so I only checked the length, but not negative indices.
if (row < returnValue.length && column < returnValue[row].length - 1 && returnValue[row][column+1] == 0) column++;
else {
row++;
direction = "down";
}

Related

How to check if there are 3 consecutive 1s in array in java?

simple example: array[6]
[1 1 1 0 0 0]
It is ok to have 3 of 1s in array but can not be consecutive.
If there are 3 consecutive 1s in a row, return false.
here is my code i am working on. I am trying y-(y-1)-(y-2) ==-1, return false but I cant make it work
Please show me good way to do it
I cannot find solutions on internet so if you know please direct the link.
New fixed: change from int[][]grid to int[] arr. Sorry for confusion
public static boolean checkOK(int[] arr) {
int limit = 3; //amount of number 1 can hay in each row and column
int countOne = 0;
for (int y = 0; y < grid.length; y++) {
if (arr[y] == 1)
countOne++; // increment countOnes
}
if (countOne > limit) { // false if amount of value 1 over 3
return false;
}
if (countOne == limit) {
// checking 3 consecutive 1s in array here?
return false;
}
return true;
}
for array above output should return false
I think your solution is close (apart from the syntax errors in your post).
The problem is that you are simply counting the number of 1's in the array, then after processing all of the elements in the array checking if there are three.
This would result in you getting a "false" return if there are three 1's anywhere in your array - contiguous or not.
The alternative is to increment the counter if you see a 1 like you are doing, but if you see something else, reset the counter to 0. Then, and this is the important bit, inside your loop check to see if you have reached the limit. If you have, then return false at that time.
The other problem that you might encounter is if your array has less than three elements in it. If you use logic such as array[i] == 1 && array[i-1] == 1 ... then you will either encounter index out of bounds exceptions and/or more complicated logic trying to avoid those exceptions.
Following is a full working example that addresses both problems.
package sequencechecker;
/**
* #author gmc
*/
public class SequenceChecker {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
SequenceChecker sc = new SequenceChecker();
int [] data = new int [] {1,1,1, 0, 0, 0};
sc.test (data);
data = new int [] { 1, 0, 1, 0, 1, 0};
sc.test(data);
data = new int [] {1, 1};
sc.test(data);
}
public void test(int [] array) {
System.out.print("for: ");
for (int i : array) {
System.out.print(i + " ");
}
System.out.println(check(array));
}
public static final int LIMIT = 3;
public boolean check(int [] array) {
int cntr = 0;
for (int i : array) {
if (i == 1) {
cntr++;
} else {
cntr = 0;
}
if (cntr >= LIMIT) {
return false;
}
}
return true;
}
}
The output is as follows:
for: 1 1 1 0 0 0 false
for: 1 0 1 0 1 0 true
for: 1 1 true
Keep track of the count of consecutive 1s and exit the loop if you hit 3.
static boolean checkOK(int[] arr)
{
int count = 0;
for(int i=0; count < 3 && i < arr.length; i++)
count = (arr[i] == 1) ? count + 1 : 0;
return count < 3;
}
Test
int[][] tests = {
{},
{1},
{1,1},
{1,1,1},
{0,1,1,1},
{1,1,1,0},
{0,1,1,1,0},
{0,1,0,1,0}
};
for(int[] test : tests)
System.out.format("%s : %s%n", Arrays.toString(test), checkOK(test));
Output:
[] : true
[1] : true
[1, 1] : true
[1, 1, 1] : false
[0, 1, 1, 1] : false
[1, 1, 1, 0] : false
[0, 1, 1, 1, 0] : false
[0, 1, 0, 1, 0] : true
Try this one:
public static void main(String args[]) {
int[] array = new int[]{1, 1, 1, 0, 0, 0};
System.out.println("IS OK? : " + checkOK(array));
}
public static boolean checkOK(int[] array) {
for(int i = 0; i < array.length; i++) {
if(!valid(array, i))
return false;
}
return true;
}
static boolean valid(int[] array, int index) {
if(index < 1 || index >= array.length - 1)
return true;
return !(array[index - 1] == array[index] && array[index] == array[index + 1]);
}
Does my code work for your problem?
int[] grid = new int[]{1,1,1,0,0,0};
for (int y = 0; y < grid.length - 2; y++) {
if (grid[y] == 1 && grid[y] == grid[y+1] && grid[y] == grid[y+2]) return false;
}
I'm not sure if the method needs to check if there are at least three, or if there are exactly three. This one is for at least three 1s (I don't have enough reputation to ask via comment).
This is the most straight foward approach I could think of, just having a counter and checking if it got to 3.
int countOne = 0;
for (int y = 0; y < grid.length && countOne < 3; y++) {
if (grid[y] == 1)
countOne++;
else
countOne = 0;
}
return countOne != 3;
One could at first put the countOne < 3 as a condition inside the loop with a break, as follows:
int countOne = 0;
for (int y = 0; y < grid.length; y++) {
if (grid[y] == 1) {
countOne++;
if (countOne == 3)
return false;
}
else
countOne = 0;
}
return true;
It's just that my teachers always insisted on not putting breaks inside loops unless you really need to.
The last return is true because there's no way to get out of the loop with three 1s as the method already returned false inside.
Try this.
int[] ar = {1,1,2,1,2,2,2,1,2,1,2,1,1,1,2,1,2,1,1};
System.out.println(isValid(ar));
int[] ar1 = {1,1,2,1,2,2,2,1,2,1,2,1,1,2,1,2,1,1};
System.out.println(isValid(ar1));
Prints
false
true
This simply counts up to three. If a digit not 1 is encountered, the count is reset to 0.
as soon as three consecutive 1's are found, the method returns false.
public static boolean isValid(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 1) {
count++;
if (count == 3) {
return false;
}
} else {
count = 0;
}
}
return true;
}
You can try this simple algorithm that increments if the item equals to one and reset it is zero, then check if the count greater than or equal to exceed then return false
public static boolean checkOK(int[] arr, int exceed) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 1) count++;
else count = 0;
if (count >= exceed)
return false;
}
return true;
}
, Main
public static void main(String[] args) {
System.out.println(checkOK(new int[] { 1, 1, 1, 0, 0, 0 }, 3));
System.out.println(checkOK(new int[] { 1, 0, 0, 1, 1, 1 }, 3));
System.out.println(checkOK(new int[] { 0, 1, 0, 1, 0 }, 3));
System.out.println(checkOK(new int[] { 0, 1, 1, 1, 0 }, 3));
}
, output
false
false
true
false

finding first even element and outputting index

My program:
public static void evenval (int[] array ){
int even=0;
for (int r = 0; r < array.length; r++) {
while (r == array[r]) {
if (array[r] % 2 ==0) {
even = array[r];
System.out.println("The first even number's index is:"+array[r]);
}
I'm trying to make a loop where it finds the first even number in an array and get it to output it's index to the main method.
I'm stuck, please help.
Try to use just for loop like this:
int even = 0;
for (int r=0;r<array.length;r++){
if (array[r] % 2 ==0){
even = r;
break;
}
}
System.out.println("The first even number's index is:"+ even );
Using the break; when find the even number.
For example if you want to find 100th even number use this:
int even = 0;
int count = 0;
for (int r=0;r<array.length;r++){
if(array[r] % 2 ==0){
if(count !=100){
count++;
}else{
even = r;
break;
}
}
}
System.out.println("The first even number's index is:"+ even );
It's better to create a small method in your class and call it from main to do this for you and return the index or -1 if a valid even number is not found. :
public class EvenTest{
int getFirstEvenIndex(int[] array){
for (int r=0; r < array.length; r++){
if (array[r] % 2 ==0){
return r;
}
}
return -1;
}
public static void main(String... args){
int[] arr = [3,5,1,2,7,8];
EvenTest et = new EvenTest();
System.out.println("First even is at index: " + et.getFirstEvenIndex(arr));
}
}
class test {
public static void main(String[] args) {
int[] array = {5, 7, 1, 8, 9, 3,110};
int evenCount =2;//required count ....for 100th even put evenCount = 100;
evenval(array,evenCount);
}
public static void evenval(int[] array,int evenCount) {
for (int i=0;i<array.length;i++) {
if(array[i] % 2 == 0&&--evenCount==0) {
System.out.println("the required even number is "+array[i]+" at index "+i);
return;
}
}
}
}
Just remove while statement in your code.
int even = 0;
for (int r = 0; r < array.length; r++) {
if (array[r] % 2 == 0) {
even = array[r];
System.out.println("The first even number's index is:" + array[r]);
}
}
If you want to stop after finding first even number, just put break inside if statement
int even = 0;
for (int r = 0; r < array.length; r++) {
if (array[r] % 2 == 0) {
even = array[r];
System.out.println("The first even number's index is:" + array[r]);
break;
}
}
You could simply use a bitwise operation as well (performance wise, it's quicker):
for (int n : array) {
if ((n&1) == 0) {
System.out.println("The first even number's index is:" + n);
break;
}
}

program running with showing progress bar in netbean but result does not come [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am defining an array to be a 121 array if all its elements are either 1 or 2 and it begins with one or more 1s followed by one or more 2s and end with same number of 1s that it begins with.
However i am not getting result while I was running my program.If program was ok I must get result 1 for given array {1,1,2,2,2,1,1}.
please help me.
public class OneTwoOne {
public static void main(String[] args) {
System.out.println(OneTwoOne.is121Array(new int[]{1, 1, 2, 2, 2, 1, 1}));
}
public static int is121Array(int[] a) {
int i, t1 = 0, t2 = 0, te = 0, tb = 0, tc = 0;
for (i = 0; i < a.length; i++) {//checking 1's and 2's in an array
if (a[i] == 1) {
t1 = 1;
}
if (a[i] == 2) {
t2 = 2;
}
}
for (i = 0; i < a.length; i++) {//counting number of 1's at begining of array
while (a[i] == 1) {
tb++;
}
break;
}
for (i = a.length; i >= 0; i--) {//counting number of 1's at end of array
while (a[i] == 1) {
te++;
}
break;
}
for (i = 0; i < a.length; i++) {//counting total number of 1's in an array
if (a[i] == 1) {
tc++;
}
}
if (t1 > 0 && t2 > 0 && t1 == t2 && te + tb == tc) {
//1's and 2's must be greater thna 0 and begining 1's and end 1's must be equal
//their sum is equal to total 1's in an array
return 1;
} else {
return 0;
}
}
}
You are using while loop instead of "if" clause, also the for loop limit is also unnecessarily long enough which is causing wrong result. I have made some changes in your method:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
//StackOverflow question.
//http://stackoverflow.com/questions/32045039/array-elements-beginning-and-ending-with-1s-by-equal-number-at-both-end-and-oth/32045312#32045312
/* Name of the class has to be "Main" only if the class is public. */
class OneTwoOne {
static int i, t1 = 0, t2 = 0, te = 0, tb = 0, tc = 0;
public static void main(String[] args) {
int a [] = new int[]{1, 1, 2, 2, 2, 1, 1};
int retunValue = OneTwoOne.is121Array(a);
System.out.println("Number of 1s in starting ::"+te +"\n Number of 1s in the end ::"+ tb +"");
System.out.println("Return value :: "+retunValue );
}
public static int is121Array(int[] a) {
for (i = 0; i < a.length; i++) {//checking 1's and 2's in an array
if (a[i] == 1) {
t1 = 1;
}
if (a[i] == 2) {
t2 = 2;
}
}
int length = a.length;
for (i = 0; i < length/2; i++) {//counting number of 1's at begining of array
if (a[i] == 1) {
tb++;
}
}
for (i = a.length-1; i >= length/2; i--) {//counting number of 1's at end of array
if (a[i] == 1) {
te++;
}
}
if (te == tb)
return 1;
else
return 0;
}
}
You may run this program here. You may access the complete code here.

Cinema seating arrangement

I'm wondering if anyone can help me, Im trying to create a simple cinema seating arrangement, where the x's are seats take and the o's are free. Problem is I cant seem to get the 0's to start where the X's finish. I'm new to java so what you see is the extent of my ability so far. Thanks for any help you can give at all!
public class Exercise4iv {
public static void main(final String[] args) {
int seats, taken, available, i, k;
seats = 50;
taken = 28;
available = seats - taken;
i = 0;
k = 0;
while (i <= taken) {
i++;
System.out.print("\t X");
if (i % 8 == 0) {
System.out.println();
}
}
while (k <= available) {
k++;
System.out.print("\t O");
if (k % 8 == 0) {
System.out.println();
}
}
}
}
if (k % 8 == 0) {
if you change this to
if ((k+taken+1) % 8 == 0) {
then it should correctly know when to print a newline
change second while loop to:
while( i<seats){
i++;
System.out.print("\t O");
if(i%8==0) System.out.println();}
}
this way the variable k is not required

Small Straight - Method

I've been stuck on this method for a couple of days now. This method checks to see if the roll of 5 dice == a small straight. It works for some numbers. If I roll a
1, 2, 4, 3, 6
it will work. However, if I roll a
1, 2, 4, 3, 3
it will not work. I think it's because of the duplicate 3 in there. I need to move it to the end somehow.
A small straight is when there are four consecutive die face values, such as 1, 2, 3, 4 or 3, 4, 5, 6. It can be in any order such as 2, 3, 1, 4
int counter = 0;
int score = 0;
boolean found = false;
Arrays.sort(die);
for (int i = 0; i < die.length - 1; i++)
{
if (counter == 3)
found = true;
if (die[i + 1] == die[i] + 1)
{
counter++;
}
else if (die[i + 1] == die[i])
{
continue;
}
else
{
counter = 0;
}
}
if (found)
{
score = 30;
}
else
{
score = 0;
}
return score;
}
The duplicate 3 is not what is throwing off the algorithm. The issue is that you check for the straight during the iteration AFTER it occurs. Thus, if the last die is part of the straight, it won't be recognized.
To fix this, move
if (counter == 3) found = true;
to the END of the loop. Should work.
EDIT: So it looks like this.
for (/*...*/) {
/* Everything else */
if (counter == 3) {
found = true;
break;
}
}
EDIT: First, if a small straight is three in a row, then you want to see if the counter gets to 2, not to 3. 3 would demand a four in a row.
Edit the start of the for loop as follows:
for (int i = 0; i < die.length ; i++)
{
if (counter == 2)
found = true;
if (i == die.length - 1) break;
//method continues here
Reasoning: I imagine that when you started coding this method, it was throwing IndexOutOfBoundsExceptions when it got to the last die in the array, tried to compare it to the nonexistant sixth die and died. So, you made the loop stop one short. But if it stops one short and the small straight is finished on the very last dice, then you never got into the loop again to confirm that the counter was 3 and a small straight had occured. By editing the start of the loop this way it goes all the way to the last element, checks and then breaks.
Alternatively, do one last check after the loop ends:
for (int i = 0; i < die.length - 1; i++)
{
if (counter == 2)
found = true;
if (die[i + 1] == die[i] + 1)
{
counter++;
}
else if (die[i + 1] == die[i])
{
continue;
}
else
{
counter = 0;
}
}
found = (counter == 2); // or counter >= 2 if you want larger straights to be found too
//continue method here
This should calculate the longest sequence:
int longestSequence(int[] a) {
Arrays.sort(a);
int longest = 0;
int sequence = 0;
for (int i = 1; i < a.length; i++) {
int d = a[i] - a[i - 1];
switch (d) {
case 0:
// Ignore duplicates.
break;
case 1:
sequence += 1;
break;
default:
if (sequence > longest) {
longest = sequence;
}
break;
}
}
return Math.max(longest, sequence);
}
You could add code such as
for (int i = 0; i < (die.length-1); i++)
{
if (die [i] == die[i+1])
{
die[i+1] =1;
}
}
Arrays.sort(die);
This will set the code for example from 1,2,3,3,4 to 1,1,2,3,4 so your code should then work.

Categories

Resources