How do I fix java.lang.ArrayIndexOutOfBoundsException: 2? [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I'm writing a program which utilizes OOP. The program I am creating is supposed to recruit applicants to a team. In my Team.java, I created a method which is supposed to accept members and add it to the team. This is a snippet of my code:
public int maxMembers;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[maxMembers] = newMember;
memberCount++;
}
I have tried this code but the line,
members[maxMembers] = newMember;
keeps throwing an error java.lang.ArrayOutOfBoundsException: 2
I have tried using a for loop in adding a new member but it does not do what I expected. Can anyone assist me in finding a solution?

You have to assign maxMembers a value in the first line, otherwise your array will have 0 elements.
public int maxMembers = 10;

Firstly, you did not initialize the variable maxMembers.Also, in the code, the line members[maxMembers] = newMember; would always put your entry in the end of the array, I think thats not the intended use of your method, public void addMember(Member newMember)
Rewriting your method would look like,
public int maxMembers=somePositiveInteger;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[memberCount] = newMember;//here
memberCount++;
}

Initialize the array with a value so that number of elements in array can be decided.

Related

why do I get an ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I keep an error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0" even though i've referenced this array bounds in the method.
`public class USCrimeLibrary
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
USCrimeObject crimeObject = new USCrimeObject(args[0]); `
and the reference object:
`public class USCrimeObject {
private Crime[] crimes;
String fileName = "/Users/jpl/Developer/Java/CMIS141/WK8/Crime.csv";
public USCrimeObject(String fileName) {
this.crimes = new Crime[20];
readFile(fileName);
}`
First of all you have to pass an argument while running the program.
But from your code I think a slight change in your code can make it executable without passing argument while running the program.
Change constructor USCrimeObject to
public USCrimeObject() {
this.crimes = new Crime[20];
readFile(fileName);
}
and from main class create USCrimeObject without argument
USCrimeObject crimeObject = new USCrimeObject();

How to get around array.equals(otherArray) evaluating to null? [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 trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:
Salesperson[] staffList;
staffList = new Salesperson[20];
Here is the loop in question, the if statement is the line that throws the NPE:
for(i = 0; i < staffList.length; i++)
{
if(staffList[i].getID().equals(idNum))
{
duplicateID = true;
}
}
Here is the class for the Salesperson array:
public class Salesperson
{
private String name;
private String idNum;
private double annSales;
//Various getter and setter methods here
}
If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!
You can update your code something like below to avoid NPE.
Salesperson[] staffList;
staffList = new Salesperson[20];
for(int i = 0; i < staffList.length; i++)
{
Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.
System.out.println("sales =" + sales); // sales = null
if(sales != null) {
if (sales.getId().equals(idNum)) {
//Do something..
}
}
}

Null Pointer Exception Error message [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I cannot seem to find why I am getting this error message. I thought I have already instantiated my array in my main.
Exception in thread "main" java.lang.NullPointerException
public class A1ArrayList<E> {
private E[] e;
private int capacity = 0;
public A1ArrayList(){
}
public int size(){
return e.length;
}
public boolean add(E addElement){
e[capacity] = addElement;
capacity = capacity + 1;
return true;
}
public static void main(String[] arg){
A1ArrayList<Object> e = new A1ArrayList<Object>();
e.size();
}
You have to initialize your array. Right now you have a field e that has place for an Array of E. But there's no array in that field! So if you try e[capacity] = addElement; you will try to add something to nothing, which is why you'll get a null pointer.
In your constructor you could use this to initialize the array.
public A1ArrayList(){
E=new E[5];
}
Like that you have an Array where you can store 5 instances of E.
Your Array e is null. Therefore you get a Nullpointer Exception.

Void function returns changed array, but not a changed integer? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
{
int[] n = new int[4];
n[0]=1;
n[1]=3;
n[2]=4;
n[3]=5;
for(int i=0; i<4; i++)
{
System.out.print(n[i]+ " ");
}
menjava(n);
System.out.println();
for(int i =0;i<4;i++)
{
System.out.print(n[i]+ " ");
}
}
public static void menjava(int[] a)
{
a[0]=1*10;
a[1]=3*10;
a[2]=4*10;
a[3]=5*10;
}
}
http://imgur.com/0CNqY9A //the result in console
{
int n = 1;
System.out.println(n);
menjava(n);
System.out.println(n);
}
public static void menjava(int st)
{
st = 4;
}
}
http://imgur.com/dAqzuez //the result in console
So why did the Array get returned, but the integer stayed the same (whcih in my mind should). I can't find anything on why the array get's returned in an void function.
The reference to the array is not returned nor changed.
The array referenced has been changed.
int[] n = new int[4];
In this code n is a reference to an array and this reference is copied when you pass it to a method. This reference is not changed.
Your issue here is that Java is a pass by value language. This means in your situation you are providing your method menjava with what might as well be a temporary array that contains the same values as your original array n. So when this array is passed to menjava it does the calculations, but to this temporary array that your main method doesn't know about.
The easiest fix here is to have your menjava method return the array it worked on and set your array to that value in the calling function something like this:
public static int[] menjava(int[] a){
//changes to array a
return a;
}
and then in your calling function:
{
//your other code
n = menjava(n);
//the rest of your code
}

Using while loop, issue with referencing from static context [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 7 years ago.
Currently I am working on an assignment within BlueJ.
The question I have is simple (I hope). The method I wish to use within the while loop is "getRearWheelDrive()" which checks how many Lamborghinis within the ArrayList< Lamborghini > inventory have rear wheel drive. rearWheelDrive is a boolean variable.
Also I can not use a for-loop for this question, otherwise I would as it would be much easier. I am limited to the while loop.
The error message I receive is: "non-static method getIsRearWheelDrive() cannot be referenced from a static context" -I tried to create a static method but it didn't work either.
//
How do I check all the Lamborghini objects within the ArrayList library and then return an int value of how many total have rearWheelDrive? Also with the current code I have, would it cause the loop to finish once it got to the end of the index, or would it infinitely loop?
public int howManyAreRearWheelDrive()
{
int indexPlace = 0;
int number = 0;
int i = 0;
while(indexPlace <= inventory.size())
{
indexPlace++;
inventory.get(i);
i++;
if(Lamborghini.getIsRearWheelDrive() == true) {
number++;
}
}
return number;
}
Without seeing the rest of the relevant classes in play here:
while(indexPlace < inventory.size())
{
if(inventory.get(indexPlace++).getIsRearWheelDrive() == true) {
number++;
}
}
You need to call getIsRearWheelDrive from an instance of the Lambroghini class not from the class itself. Only static variables can be called using the class name which is not the case here.
In this example it would be
inventory.get(i).getIsRearWheelDrive();

Categories

Resources