Java Array object problem
Hi,
i'm going to come right out and say im working on a project for my college course and i need some help with a specific problem i am having. I don't expect anyone to do my work for me but just possibly tell me why i am getting this error.
so i'm working on a betting program, very simple dulled down one and the class i'm having problems with is a class that reads from a text file that has the names of the teams inside of it and simply puts those names into an array. simple enough but somehow is giving me a problem.
so here is my code:
Code:
import java.io.*;
import java.util.Scanner;
public class Team {
String[] team = new String[3];
int a = 0;
FileReader stats = new FileReader("C:/team.txt");
Scanner statss = new Scanner(stats);
public Team() throws Exception{
do{
team[a] = statss.nextLine();
System.out.println(team[a]);
a++;
}while (statss.hasNext());
}
}
so i have it printing just so i can see what is happening, and i have my main class where i call this team object and just tell it to print. my text file just simply has in this order 4 team names:
ManUtd
Liverpool
Chelsea
Arsenal
there are no extra spaces or anything in the text file.
so when i run my main class which is just:
Code:
public class Main {
public static void main(String[] arg) throws Exception {
Team test = new Team();
System.out.println(test);
}
}
this is the output i get:
Code:
run:
Man Utd
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
Liverpool
chelsea
at betprog.Team.<init>(Team.java:21)
at betprog.Main.main(Main.java:19)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
if i change my array to size 4 this is what i get:
Code:
run:
Man Utd
Liverpool
chelsea
arsenal
betprog.Team@b66cc
BUILD SUCCESSFUL (total time: 2 seconds)
i know this has to be a simple logical error i'm making somewhere and i'm guessing it has to do with my loop, i've tried both while and do while and both give the exact same result.
but yea im kind of stumped and i know i'm a noob but any help would be greatly appreciated.
Thanks