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

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);
}

Related

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...) {
...
}

Removing an array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Removing an element from an Array (Java) [duplicate]
(15 answers)
Closed 4 years ago.
Got a simple auction program running, only problem is that if a user is removed before auction is closed his/hers bids are supposed to be removed. I dont have it 100% down yet but I think I am on the right path.
The bids have to be arrays and right now it is kinda removed or just moved maybe. This was a the error earlier.
Top Bid:[Wow 400 kr, Boy 311 kr, Man 33 kr, Dude 2 kr]
command>remove user
Name>wow
Wow has been removed from registry
command>list auctions
Auction # 1: Item. Top Bid:[Boy 311 kr, Man 33 kr, Exception in thread "main" java.lang.NullPointerException
public void removeBid(String name) {
for(int a = 0;a < bidIndex; a++) {
if(bids[a].getUser().getName().equals(name)) {
bids[a]=null;
bidIndex--;
break;
}
}
sortBids();
public void sortBids() {
if(bidIndex > 1) {
for(int a = 0; a < bidIndex -1; a++) {
for(int b = a + 1; b < bidIndex; b++) {
if(bids[a] == null || bids[a].getBid() < bids[b].getBid()) {
Bid temp = bids[a];
bids[a] = bids[b];
bids[b] = temp;
}
}
Arrays cannot change size once initialized. If you create an array new String[10]; it will forever have 10 items (which are null by default). Setting an index to null doesn't change this.
String[] items = new String[] {"String1", "String2", "String3"};
items[1] = null;
This arrays would now look like [String1, null, String3].
If you need to change arrays as much as it seems, you're better off using a List or Map.
I would suggest using a HashMap if you want to easily link one object to another. In this case it looks like you'd be linking a String (name) to the Bid object.
Map<String, Bid> bids = new HashMap<String, Bid>();
Bid bid1 = new Bid(/*...*/);
Bid bid2 = new Bid(/*...*/);
// Add bids to the map
bids.put("Wow", bid1);
bids.put("Boy", bid2);
// Get any of these objects
Bid retrievedBid = bids.get("Wow");
// Or remove them
bids.remove("Wow");
HashMaps are similar in concept to associative arrays from other languages, where you have a key -> value relationship. Each key is unique, but the value can repeat.
They can also be converted to arrays if the final result you need is an array.
Bid[] bidsArray = new Bid[0];
bidsArray = bids.values().toArray(bidsArray);
One way you can achieve this is to convert the array to a list and then remove the bid using Java streams and convert back.
List<Bid> bidsList = Arrays.asList(bids);
bidsList = bidsList.stream()
.filter(n -> !n.getUser().getName().equals(name))
.collect(Collectors.toList());
bids = bidsList.toArray(new Bid[bidsList.size()]);

Can we use "catch" to handle OutOfBoundsException with specific value?

I'm learning about exceptions in java. I have come across the following problem:
String bigstring = myscanner.nextLine();
String[] splited = bigstring.split("\\s+");
try {
smallstring1 = splited[0];
smallstring2 = splited[1];
smallstring3 = splited[2];
} catch(java.lang.ArrayIndexOutOfBoundsException exc) {
smallstring3 = null;
}
This would work if the user wants to type 2 words only.
What if he wants to type one word?
Can we somehow specify a value which we get in error after the colon?
Like:
java.lang.ArrayIndexOutOfBoundsException: 2
or
java.lang.ArrayIndexOutOfBoundsException: 1
Can we somehow use (for this example) this "2" or "1" in try/catch block?
java.lang.ArrayIndexOutOfBoundsException is not a exception designed to be recoverable. It conveys a programming error.
So rather than trying to understand the index that causes problem in the catch, you should rather ensure that the exception doesn't occur.
In your case you should check the size of the array before trying to get the value of it.
Here is an example :
int arraySize = splited.length;
if (arraySize == 3){
smallstring1=splited[0];
smallstring2=splited[1];
smallstring3=splited[2];
}
else if (arraySize == 2){
smallstring1=splited[0];
smallstring2=splited[1];
}
else if (arraySize == 1){
smallstring1=splited[0];
}
You probably shouldn't use exceptions for normal program flow. Exceptions should usually be "exceptional".
Anyway, although you cannot do that, you can use if statements inside your catch block. You can also check splited.length to check how big the array is.

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.

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

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.

Categories

Resources