java code keeps throwing exception - java

My code always throws an exception java.lang.String.charAt at this line in my code :
while(0 == charToInt(value.charAt(startValueAt))){
in the code segment,
private static ArrayList<Integer> stringToArray(String value){
ArrayList<Integer> holder = new ArrayList<Integer>();
int startValueAt = 0;
if(value.charAt(0)=='-'|| value.charAt(0)=='+')
startValueAt= 1;
else
startValueAt = 0;
while(0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
}
int startOfValue = value.length() - (startValueAt - 1);
//to make sure that arraylist is right size and last element ends up at zero as well as find starting index of j with above step
//we use value of startValueAt
for(int i = startOfValue, j = startValueAt; j <= value.length() - 1; i--, j++){
holder.add(0, charToInt(value.charAt(j)));
}
return holder;
}
Here is the stack trace:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at BigInt.stringToArray(BigInt.java:145)
at BigInt.<init>(BigInt.java:35)
at BigInt.multiplyBySingleDigit(BigInt.java:853)
at BigInt.multiplyPositives(BigInt.java:878)
at BigInt.multiplyOneNegative(BigInt.java:920)
at BigInt.multiply(BigInt.java:778)
at BigInt_Add_Sub_Mul_Div_Mod_Demo.main(BigInt_Add_Sub_Mul_Div_Mod_Demo.java:164)

while(startValueAt < value.length() && 0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
}
You are ignoring the case where the String is all 0s. Then you will call value.charAt(value.length()) which throws the exception.

Using the string "+321", by the last for loop the variable 'j' is set to startValueAt and is supposedly pointing to the last integer, i.e. '1'. In other words the 4th character in '+321'. But then you increment 'j' (with j++) and try to find it in the array. This will give you an out of bounds exception.

while(0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
if (startValueAt>=value.length()) break; /*add this line */
}

(1) You need to make sure that value contains at least one number that is not 0 (otherwise, your while-loop will continue until it wants to get a char from value that is out of bounds / doesn't exist)
An attempt to fix this problem might be changing your while-loop to this:
while(startValueAt < value.length() && 0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
}
(2) In your for-loop:
for(int i = startOfValue, j = startValueAt; j <= value.length() - 1; i--, j++){
holder.add(0, charToInt(value.charAt(j)));
}
the variable j is incremented until it equals value.length(). The problem is, if your string has 4 characters you can access the last character using string.charAt(3).
The problem should be fixed by simply changing j <= value.length() to j < value.length().
Remember, arrays and lists always start at index 0.

Related

Out of bounds exception in double dimensional array

Trying to find the sum of all even numbers and product of all odd numbers in a double dimensional array.
Why am I getting the following out of bounds exception error ?
Exception java. lang. Array Index Out Of Bounds Exception
While running the code this exception comes for line if(m[i][j]%2==0)
The exact cause of your error is that your 2D array is actually a jagged array, meaning that not every row contains the same number of elements. In fact, the second row only contains three elements, so when you when the following if check:
if (m[i][j]%2 == 0)
you get an out of bounds exception for i=1 and j=3.
You should either make the 2D array non-jagged, or instead use this for loop:
for (int i=0; i < 4; ++i) {
for (int j=0; j < m[i].length; ++j) {
if (m[i][j]%2 == 0) {
s += m[i][j];
}
else {
r *= m[i][j];
}
}
}
}
Your m array's element at index 1 is missing a fourth element:
{30,11,71}
Do not use as limits fixed values (such as 4), but instead use the length provided by the array(s).
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
//...
}
}
Why?
Not all inner arrays have 4 elements (i.e.: {30, 11, 71}), so at the last iteration of the inner loop (j = 3), this code m[i][j] tries to access a value out of the bounds of the array because in some cases there is no position 3, just 0 (1st element), 1(2nd element) and 2(3rd element). Thus you get the mentioned exception.
Side note:
Another problem (mentioned by you) is that you will get r = 0 always because it is initialized to 0 and every time you multiply its value by another one, the result will be 0.
So, in order to fix this you need to add a check in the else condition, like this:
else {
r = r == 0 ? m[i][j] : r * m[i][j];
}

Returning the number of times a number appears in an Array?

So I'm doing a bunch of exercises, one of them asks me to write a method that is passed an array with each slot type int. This method should return the number of times 99 occurs in the array. Here's what I came up with on the fly:
public static int countNum(int[]x)
{
int count = 0;
for (int i = 0; i <= x.length;i++);
{
if (x[i] == 99)
count++;
}
return count;
}
All in all, I just need to write the method. Am I on the right track?
Well, there are two mistakes.
First: i < x.length; it should be like that or i <= x.length - 1; like that or you will get out of your array.
Second:
for (int i = 0; i <= x.length;i++)**;**
{
if (x[i] == 99)
count++;
}
You don't need ; or the next code will be out of for.
array.length returns length of an array and you don't want to iterate from 0 to length, but from 0 to length - 1.
Why? For example if an array is [1, 5] then:
array.length == 2, array[0] == 1, array[1] == 5 but array[2] throws java.lang.ArrayIndexOutOfBoundsException (because it tries to reach an element which is not in the array)
Remove the semicolon after the for statement:
for (int i = 0; i <= x.length;i++);
(a for loop executes statements which comes directly after it, and ";" ends a statement. The for(...) followed by ";" means that you have a loop which does nothing x.length times)

Does order of conditions matter with multiple conditions in a while loop?

I was not able to find the answer to this question. I was working on an insertion sort method and it wouldn't properly execute:
public static <T extends Comparable<? super T>> void insertionSort(T[] array) {
int length = array.length;
T temp;
for (int i = 1; i < length; i++) { //start of unsorted
temp = array[i]; //save the element
int j = i-1;
while (temp.compareTo(array[j]) < 0 && j >= 0) { // while temp is less than array[j]
array[j+1] = array[j];
j--;
} //end of while
array[j+1] = temp; //as soon as temp is greater than array[j], set array[j] equal to temp
}
}
This returned an ArrayIndexOutOfBoundsException on the while loop line, but when I switched the conditions in the while loop around to this:
while (j >= 0 && temp.compareTo(array[j]) < 0)
it worked. I didn't think in Java the order of conditions in a while loop mattered to the program? This is very strange to me, as I've never seen or heard of order mattering in a statement with && since I assumed that the two while loop lines were equivalent. I was stuck wondering this for a while and couldn't find an answer.
Can someone explain why this is so?
Conditions are evaluated left to right.
Initially, for case j=-1, your code wasn't evaluating the second condition because the first one was throwing an ArrayIndexOutOfBoundsException exception.
while (temp.compareTo(array[j]) < 0 && j >= 0)
However when you switched the conditions like this:
while (j >= 0 && temp.compareTo(array[j]) < 0)
then for the same case (j=-1), since first condition becomes false, then regardless of the second value, the whole condition will always be false; and so the second condition won't be evaluated and hence no exception in this case.
Lets consider the following example:
boolean b = Condition_1 && Condition_2;
Now if the Condition_1 is always false then whatever the value of Condition_2, b will always be false. So when first condition is false of an 'and' then no need to check the value of second condition that is what exactly happened here.
It's exactly error if you use the condition while (temp.compareTo(array[j]) < 0 && j >= 0)
In Java, it checks condition && first and then checks || after.
In the condition && it checks in the order.
Therefore, in your case while (temp.compareTo(array[j]) < 0 && j >= 0), it check this condition temp.compareTo(array[j]) firstly. If j out of the array index, ==> you get error
When you change the condition to while (j >= 0 && temp.compareTo(array[j]) < 0), it check j>=0 firstly, if j = -1 the program cannot go further.

StringIndexOutOfBounds in Java

I have two exact copies of code here, except one has '<' in the for loops while the other has '<='. Could someone please explain why I get the index out of bounds exception when I use '<=', but then it works fine with '<'
Error code:
for(int i = 0; i <= str.length(); i++) {
int count = 0;
char currentChar = str.charAt(i);
for(int j = 0; j <= str.length(); j++) {
if (currentChar == str.charAt(j) ) {
count++;
Working code:
for(int i = 0; i < str.length(); i++) {
int count = 0;
char currentChar = str.charAt(i);
for(int j = 0; j < str.length(); j++) {
if (currentChar == str.charAt(j) ) {
count++;
If I don't use <= how will it compare the last character in the string?
Valid String indexes in Java, just like the indexes in any array, go from zero to length minus one. So clearly if you set up your condition to go up to i <= str.length(), you'll get outside the string.
Remember that a String on the inside is nothing more than a char[], and again: the valid indexes go from 0 to length-1. This is a convention, followed by many other programming languages that decided to start counting from zero instead of one.
Because you cannot access str.chatAt(str.length()) without throwing a exception.
a < b means "a is less than b" and it will be false when a equals to b.
a <= b means "a is less than or equals to b" and it will be true when a equals to b.
To compare the last character in the string, write some code to do so, compile and run.
bool res = currentChar == str.charAt(str.length() - 1); // assuming str has string with one character or more
str.length() returns the number of characters in the String. So "String".length() returns 6.
Now, when using indices, you start with zero. so "String".charAt(0) returns 'S'. "String".charAt(6) gives you a StringIndexOutOfBoundsException because the last character in "String" is at index 5.
String indexes begin at 0. str.length() returns how many elements are in your array. if you have a string
"dog"
"dog".length() = 3,
'd':0, 'o':1, 'g':2.
Since your for loop initializes i to 0, the working loop goes through indexes 0-2, which is 3 values, while the non-working one goes 0-3, and references a null, and str.charAt(3) does not exist.

array index out of bounds not fired

public static void insertionSort(int[] data) {
for (int i =0; i < data.length; i++) {
int current = data[i];
int j = i-1;
while (j >=0 && data[j] >= current) {
data[j+1] = data[j];
j--;
}
data[j+1] = current;
}
}
the line while (j >=0 && data[j] >= current) should throw array index of bounds when data[-1] for the first time. I dont understand why it does not. Can some one please help
Thank you
Ashok Pappu
Boolean expressions like these are never fully evaluated if the condition can be met earlier.
So...in your case since j >= 0 is false and false && ??? will always be false the second part does not need to get evaluated. This is why data[-1] will never be called.
You can use the same principle for null checks, e.g.
if (object != null && object.isSomething())
If while clause contains more, than 1 expression, splitted by &&, they are executed one by one. This is done to increase performance.
I.e. at first in your code j >= 0 will checks. If j < 0, it false. So, cycle will be interrupted regardless of the 2nd expression.

Categories