How can i avoid ArrayIndexOutOfBoundsException in this case? [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
Is it possible to avoid ArrayIndexOutOfBoundsException in this case ??
package com;
public class Hi {
public static void main(String args[]) {
String[] myFirstStringArray = new String[] { "String 1", "String 2",
"String 3" };
if (myFirstStringArray[3] != null) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
}
}

Maybe I don't understand the real problem, but what prevents you to check if the index is inside the array before accessing it in this case?
if (myIndex < myFirstStringArray.length) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}

In arrays, they are measured differently than numbers. The first object inside an array is considered 0. So, in your if statement, instead of a 3, you just put a 2.
if (myFirstStringArray[3] != null) {
System.out.println("Present");
to
if (myFirstStringArray[2] != null) {
System.out.println("Present");
Hope this helps! :)

Your String array contains 3 elements and you are accessing array[3] i.e. 4th element as index in 0 based and so you get this error (Exception, anyway).
To avoid the ArrayIndexOutOfBoundsException use an index within specified index range. And always check whether your index is >= array.length.

Related

I have a problem with "variable may not have been initialized" despite having an if/else statement (initialization in both cases) [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Why does this code keep returning a "variable might not have been initialized" error?
(2 answers)
Java variable might not have been initialized? [closed]
(4 answers)
Closed 2 months ago.
protected int getGewichtung(String company)
{
int index;
for (HashMap<String,String> i : top3Compland)
{
String test = String.join(_name, i.keySet());
System.out.println(test);
if (test == company)
{
index = top3Compland.indexOf(i);
}
else
{
index = -5;
}
}
return index;
}
I have checked with print statements whether it is entering the for-loop at all. But all the keys are being printed out so it does enter it and also the conversion to a string does take place and as I am at first putting only valid strings to the function it also must enter the if statement for sure but if even it doesn't then it would be enter the else statement and initialize it with a number so it should't be complaining about the variable "index" possibly not being initialized. What am I overseeing?? Thank you for your help!
updated Version: I improved some flaws, but the same error is arising. But I cannot fathom a case in which index is not being initialized...
protected int getGewichtung(String company)
{
int index;
if (top3Compland.size() > 0 && top3Compland != null)
{
for (HashMap<String,String> i : top3Compland)
{
String test = String.join(_name, i.keySet());
System.out.println(test);
if (test.equals(company))
{
index = top3Compland.indexOf(i);
}
}
}
else
{
index = -5; //company not found
}
return index;
}
You do have an initialization in both if/else statements, however this only applies when you enter the foreach loop. When top3Compland is empty the program doesn't enter the loop and the variable index is never initialized.

Why am I getting a NullPointerException for this loop? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm writing a for loop to iterate through the array and find the index of the employee with the social security number of 123456789. Why do I keep getting a NullPointerException?
.getSocSecNum() returns a String
empnew[21] = Empthe1;
String temp = "123456789"
for(int i = 0; i < empnew.length - 1; i++){
if(empnew[i].getSocSecNum().compareTo(temp) == 0){
System.out.println("the location of the employee is " + i);
}
}
I want it to output "the location of the employee is 21" but all I get is a NullPointerException
The problem is most likely that empnew has at least one null in it.
So in the loop, you try to get empnew[i].getSocSecNum(), which expands to null.getSocSecNum(), which gives you a null pointer exception, because you can't access class members on null, because it isn't a real object.
The easiest solution might be to just check that empnew[i] != null before accessing the value:
if (empnew[i] != null && empnew[i].getSocSecNum...) {
...
}

Error message being thrown: Index out of bounds exception [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
For the following code I am getting an index out of bounds exception and I am not sure as to why. Any help is greatly appreciated.
public Rabbit nearestRabbit()
{
List<Rabbit> rabbits = this.getWorld().getObjects(Rabbit.class);
if (this.getWorld().getObjects(Rabbit.class) == null)
{
return null;
}
Rabbit nearest = rabbits.get(0);
double distance = distanceTo(nearest);
for (Rabbit rabbit : rabbits)
{
double thisDistance = distanceTo(rabbit);
if (thisDistance > distance)
{
distance = thisDistance;
nearest = rabbit;
}
}
return nearest; //#######
}
This is mainly due to your list size, I know that you have checked null for the list but since the list is not null it can still be empty with the size 0 and you can not access to the element at index 0.
I recommend you to check the list size.
You are getting this exception by not checking if the index is in bounds in the call rabbits.get(0).
A simple workaround is to put this code first.
if (rabbits.isEmpty())
return null;
This checks if the list is empty before making any other calls.
Also, it would be best to refrain from reference this.getWorld().getObjects(Rabbit.class) more than once, especially after holding it as a variable which is much more accessible.
Add a size check to your if
if (this.getWorld().getObjects(Rabbit.class) == null || rabbits.isEmpty() )
A list may well not be null yet still be empty. E.g. any freshly generated one:
LinkedList<Object> objs = new LinkedList<>();
System.out.println(objs != null && objs.isEmpty()); //true
Your IndexOutOfBound is probably when you are getting element at index 0 where the list might be empty.
if (!rabbits.isEmpty())
{
Rabbit nearest = rabbits.get(0);
}

Value of Variable Not Updating [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
My Variable c is always zero. I dont understand why its not updating. can anyone please explain why this is happening. what should i do to avoid this
public static int linearSearch(Exam[] marks, String name) {
int c =0;
if( marks==null)
{
return -1;
}
else{
for(int i=0;i<marks.length;i++)
{
//System.out.println(a[i]);
if(performances[i].getName()==name)
{
c= i;
}
}
}
return c;
//to be completed
}
Modify this line as below
performances[i].getName().equalsIgnoreCase(name)
if you want to Ignore upper or lower case
else use the below
performances[i].getName().equals(name)
to check the content of the name instead of references.

NullPointerException where there's no possibility for one [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm trying to find a solution for a programme which I'm writing. The problem occurs even though I tried to prevent it and I don't seem to be able to find a mistake. This is the ''problematic'' part of my code:
if (this.s != null) {
if (s.s != null && s.s.sta.length != 0) {
for (int n = x; n < s.s.sta.length + x; n++) {
this.sos[n] = s.s.sta[n-x];
}
x = x + s.s.sta.length;
}
}
I have an array STA which I'm using and a method which gives me the ''s'' neighbour of an object, so s.s is a neighbour of a neighbour.. What I'm trying to do is copy the objects from more than one specific neighbour into one array with many different if sentences. This one is an example but it doesn't work.
Thank you and I really hope I get some info because I'm completely lost.
In the second line of your code you have:
if (s.s != null && s.s.sta.length != 0) {
You do check if s.s is null, but you do not check if s.s.sta is null.

Categories

Resources