r/javahelp • • Jan 11 '21

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at oo.Entity.create(Entity.java:8) at oo.Main.main(Main.java:6)

im coursing a game dev course and the first language its java making experiments to create an entity database for games im getting this error when i call a function see this
Entity.java

package oo;
public class Entity {
	String SNAME[];
	int SLIFE[];
	int SDAMAGE[];
	public void create(int UEID , String Name , int life , int damage) {
			System.out.println( Name + " has start entity started in UUID " + UEID + "logged on ");
			SNAME[UEID] = Name;
			SLIFE[UEID] = life;
			SDAMAGE[UEID] = damage;
	}
	public void damage(int UEIDtakingDamage , int UEIDdoingDamage) {
		SLIFE[UEIDtakingDamage] =- SDAMAGE[UEIDdoingDamage];
		if (SLIFE[UEIDtakingDamage] <= 0) {
			System.out.println(SNAME[UEIDtakingDamage] + " has dead by taking a damage of" + SNAME[UEIDdoingDamage]);
		}
	}
}

Main.java

package oo;

public class Main {
	public static void main(String[] args) {
	 Entity Obj = new Entity();
	 Obj.create(1, "Vitm", 100, 25);
	 Obj.create(2, "Assasin", 1000, 250);
	 Obj.damage(1, 2);
	}
}

Console when run Main.java

Vitm has as Player started in UUID 1logged on 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
	at oo.Entity.create(Entity.java:8)
	at oo.Main.main(Main.java:6)

im newbie in java so pwease no be angry with me by the wrong code im typed

0 Upvotes

7 comments sorted by

View all comments

5

u/Sergey305 Jan 11 '21 edited Jan 11 '21

Java array indices begin with 0, and before using an array you must initialize the variable first.

Personally, I'd abandon arrays here and switch to lists, as it's more flexible.

And follow, please, a naming convention: https://google.github.io/styleguide/javaguide.html#s5-naming. Your class' fields are somewhy UPPERCASE, and method args are also formatted somewhat randomly.