I keep getting this Array out of bounds error for the following code.
brock.txt = reflection program, routine, Arrow, snake game,
public static void main(String[] args) {
String filename = "brock.txt";
String line;
String [] cities = {};
int x = 0;
try {
BufferedReader eshread = new BufferedReader( new FileReader (filename));
line = "";
while ((line = eshread.readLine()) != null ) {
String[] store = line.split(",");
System.out.println(store[0]);
System.out.println(store[1]);
System.out.println(store[2]);
cities[x] = store[2]; //< keep getting an error here
x++;
}//end while loop
eshread.close();
}//end try
catch(IOException iox) {
System.out.println("failiure");
}//end catch
String [] cities = {} will make the array size to 0,when x is greater than 0 the error will occur,that's the reason,so you need to make cities a fixed size at first or use List to do it
You Must define the size of cities or use a list .
You initialized cities with an empty array({}), which means it has a length of 0(not an null, but an empty array). By using cities[0] you are expecting it has at least one element, which is not true.
To fix this, use an ArrayList<String> instead of a String array.
In agreement with the other comments. The issue is with the size of cities array which is being set to 0 and hence the issue for array out of bounds.
I tried the following code and it works if you want to work with a String array.
Else an ArrayList is a better solution if the size is not defined.
String [] cities = new String[10];
Related
I am working on a class assignment where we can only use arrays and no Collection classes to read a text file and fill an array with information from the text file. the file ArrayData.txt is the information bellow.
The file is formatted in this way:
3 //First line states how many sets are in the file
2 //Next line:there are x numbers in the set
10.22 567.98 //Next Line states the doubles that are in the set
//The pattern continues from there
1 // x numbers in the next set
20.55 // Double in the set
3
20.55 2.34 100.97
My issue is filling the initial array with an array, then filling the second array with the doubles.
Essentially, I want it to look like this:
initArray[0]=> smallArray[2]={10.22,5.67.98}
initArray[1]=> smallArray[1]={20.55}
initArray[2]=> smallArray[3]={20.55,2.34,100.97}
Here is what I have so far:
public static double[] largeArray;
public static double[] insideArray;
public static void main(String[] args) {
String fileInputName = "ArrayData.txt";
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader(fileInputName)));
while (sc.hasNextLine()) {
int i = sc.nextInt();
largeArray= new double[i];
for(int x=0; x<i;x++)
{
int z = sc.nextInt();
insideArray= new double[z];
for(int y=0; y<z; y++)
{
insideArray[z]=sc.nextDouble();
}
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (sc != null)
sc.close();
}
}
First off, does this logic even make sense? Secondly, I keep getting an array out of bounds error, so I know something is right, I'm just not sure where.
Remove the while. You want the body to execute only once. Line breaks at the end of the file may cause it to run again and then there will be no nextInt(). If you want to support empty files, make it an if.
Secondly, insideArray[z] = ... should be insideArray[y] = ...
Finally, largeArray should be an array of arrays double[][] (a so called jagged array) and you want to assign insideArray to the according place after filling it.
I have a class "car", having five parametres of car (str brand, str model, str colour, int power, int tank), and I have a .txt with five cars, written like that:
Toyota Supra Black 280 80
Ferrari F430 Red 510 95
Nissan GT-R White 600 71
Koenigsegg Agera White 940 80
Mazda RX-8 Red 231 62
I have to read this list from file and make an array of lines array (cars), while each car array is an array of 5 parametres, like:
Cars[car][parametres], and push it into a object of a class (should be a peace of cake, and i think i can handle this)
But i have no clue how to deal with array. Only thing i have now is reading from file:
void 123() {
String[] ImpData = null;
try {
String str;
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}
}
Any suggestions?
Create a list of Car object and adding each line into the list as 1 Car object each.
ArrayList<Car> list = new ArrayList<Car>();
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
list.add(new Car(tok[0], tok[1], tok[2], tok[3], tok[4]));
}
Assuming your Car class has a constructor which accepts the 5 arguments.
Edit: (To fit requirement of using Array)
When you use array, you have to pre-allocate a fixed array length first. Using array is not suitable for storing data from files because there can exist any number of lines of data. Anyway, to answer your question on using array:
String[][] data = new String[numRecords][5]; //numRecords equals total car objects
int x=0;
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
data[x] = tok; //Assign entire row of tok into data
x++;
}
Once again, I seriously do not recommend reading data file into an array. If you really have to do so, you can pre-determine number of records in the text file first, then set the array size accordingly.
Side note: 2D arrays are also not a suitable data structure for storing data such as a car object with its own attributes.
You want a two dimensional array. However, note that the array size must be known in advance and you don't know how many lines are in the file. So, first read everything into a secondary linked list data structure (you could also read the file twice, this is not efficient). Now you have all the strings, make a two dimensional array and then split each string into an array of tokens, using the " " delimiter. If you want to treat the tokens as integers and strings, you can use an array of Object instead and store Integer, String, etc. Off the top of my head, something like this follows - also note in your post, you can't start a method with numbers :)
String[] ImpData = null;
try {
String str;
List<String> allStrings = new LinkedList<String>();
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
allStrings.add(str);
}
br.close();
String[][] ImpData = new String[allStrings.size()][];
for(int i=0; i<allStrings.size();i++){
ImpData[i] = allStrings.get(i).split(" ");
}
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}
I think what you are looking for is a 2-dimensional array.
The first dimension is the index for the car, the second are the 5 pieces that make it up. It looks like this: (not actual language, just a guide to build it.)
array is car[int][string, string, string, int, int]
car[0][Toyota,Supra,Black,280,80]
car[1][Ferrari,F430,Red,510,95]
So, referencing car[1] will tell you all about that car.
That's one idea, anyway...
for Car
class Car {
public String brand, model, colour;
int power, int tank;
}
structure
List<Car> cars = new ArrayLis<Car>()'
the most important part is safe analize line and fill part of data. The simplest (but not the best) is:
In out loop when You have line str line by line, set analyse:
String arg[] = str.split(" ");
Car c = new Car();
c.brand = arg[0];
c,model = arg[1];
c.color = arg[2];
c.power = Integer.parseInt(arg[3],0);
c.tank = Integer.parseInt(arg[4],0);
and then
cars.Add(c);
I am getting an error when trying to use a JFileChooser to scan a text file add it to an array and parse one of the strings to a double and two to integers. Does it have to do with the fact that the addEmployee method adds the six parameters to an arrayList? Here is the code...
else if (e.getSource()==readButton){
JFileChooser fileChooser = new JFileChooser("src");
if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
empFile=fileChooser.getSelectedFile();
}
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
String[] rowData = scan.next().split(":");
if(rowData.length == 5){
rowData[4] = null;
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
else{
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
if (position2.equals("Manager")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else if(position2.equals("Sales")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else{
c.addEmployee(fName, lName, position2, firstParam, secondParam, empNum);
}
}
}
John:Smith:Manufacturing:6.75:120:444
Betty:White:Manager:1200.00:111
Stan:Slimy:Sales:10000.00:332
Betty:Boop:Design:12.50:50:244
You are trying to fetch empNum = Integer.parseInt(rowData[5]);
row data only having size 5 that means index 0-4, Thats why ArrayIndexOutOfBoundsException is getting
So Initialize String[] rowData = new String[6];
String[] rowData = new String[5]; // edited out of original post
rowData = scan.next().split(":");
The first statement allocates an array of 5 Strings and sets them all to null. The second statement just throws away the array you just allocated. The result of split will return an array of however many items it finds, and then you assign rowData, which is a reference to an array, to a reference to the new array. The old one gets garbage collected. So there's no guarantee that rowData will have 5 elements after this assignment.
You'll have to decide what you want to do if the split doesn't return enough array elements. You could use something like Arrays.copyOf that could put the split result into some of the rowData elements while leaving the rest alone, but then the unassigned elements will still be null, and you'll just get a NullPointerException a few lines later. So you have some design decisions to make here.
More: You may want to consider using the Scanner method nextLine() instead of next(). next() will return just one token, which means it will stop at a space character, which means you will have problems if someone is named "Mary Beth" or something like that.
I'm trying to sort a list of strings in array into alphabetical order without using the sort method.
public static String[] sortedAdjectives(String[] original)
{
String[] sortedArray;
int aValue = 65;
String word = "";
sortedArray = new String[25];
for(int i = 0; i <25; i++)
{
original[i]=word;
char c = word.charAt(0);
sortedArray[c-aValue]=word;
}
return sortedArray;
Is my method, and
public static void main(String[] args) throws FileNotFoundException {
Scanner names = new Scanner(new File("names.txt"));
Scanner adjectives = new Scanner(new File("adjectives.txt"));
String[] adjectiveArray;
adjectiveArray = new String[25];
int counter = 0;
while (counter<25)
{
String in = adjectives.next();
fixCapitalization(in); //method that fixes capitalization
adjectiveArray[counter]=in;
counter++;
}
sortedAdjectives(adjectiveArray);
Is where I put the items from the file into an array. I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Hmwk.sortedAdjectives(Hmwk.java:56)
at Hmwk.main(Hmwk.java:24)
When I try to run my program and I can't figure out where I'm going wrong. If you could point me in the right direction i'd be much appreciative. Thanks for your time.
You have word initialized as an empty string:
String word = "";
Then you are calling charAt(0) on an empty string. Can't do that.
Your string needs to be at least longer than 1 character in order to call that method.
You made a little mistake in the for loop.
It should probably be word = original[i]; which you did it inversely and makes the word never take the original parameter as reference.
Also a few things to improve here: using arraylist would have better extensibility and avoid erasing repetitive letters.
I have a program where I need to store the results in an arraylist:-
public class ReseedingDBRandomElements {
public static void main(String[] args){
try {
// getting the field Keyword from the csv
String csvfile="/Users/dray/Downloads/ReseedingDBRandomKeywords.csv";
BufferedReader br =new BufferedReader(new FileReader(csvfile));
StringTokenizer st = null;
String line="";
int linenumber=0;
int columnnumber;
// initializing the parameter for each column
int free = 0;
int free1 = 0;
// create the ArrayList
ArrayList<String> Keyword = new ArrayList<String>();
ArrayList<String> Alternate = new ArrayList<String>();
// reading through the csv file
while((line=br.readLine())!=null){
linenumber++;
columnnumber = 0;
st = new StringTokenizer(line,",");
while(st.hasMoreTokens()){
columnnumber++;
String token = st.nextToken();
if("Keyword".equals(token)){
free=columnnumber;
System.out.println("The value of free :"+free);
}else if ("Alternate".equals(token)){
free1=columnnumber;
System.out.println("The value of free1 :"+free1);
}
if(linenumber>1){
if (columnnumber==free)
{
Keyword.add(token);
}else if (columnnumber==free1){
Alternate.add(token);
}
}
}
}
// converting the keyword ArrayList to an array
String[] keyword = Keyword.toArray(new String[Keyword.size()]);
for(int i=0;i<keyword.length;i++){
System.out.println(" The value of the keyword is :"+keyword[i]);
}
// converting the alternate ArrayList to an array
String[] alternate = Alternate.toArray(new String[Alternate.size()]);
for(int i=0;i<alternate.length;i++){
System.out.println("The value of the alternate is :"+alternate[i]);
}
ArrayList<String> AlternateNew = new ArrayList<String>();
for(int i=1;i<keyword.length;i++){
if(keyword[i].equals(keyword[i-1])){
AlternateNew.add(alternate[i-1]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
String[] alternatenew = AlternateNew.toArray(new String[AlternateNew.size()]);
System.out.println("The length of the array is :"+alternatenew.length);
for(int i=0;i<alternatenew.length;i++){
System.out.println("the value of the alternatenew :"+alternatenew[i]);
}
}catch (Exception e){
System.out.println("there is an error :"+e);
}
}
}
The following is the csv file
Keyword,Alternate
ego kit,baby doll
ego kit,garage park
ego kit,random beats
galaxy tab,venus
galaxy tab,earth
galaxy tab,sun
What I am trying to do is compare elements and store it in an arraylist and display the results, but when last element is getting compared i.e 'galaxy tab' is getting compared to an empty field after last 'galaxy tab', it is not storing the previous result in the arraylist which is 'sun'
The following is the result of the program :
The value of the alternate is :baby doll
The value of the alternate is :garage park
The value of the alternate is :random beats
The value of the alternate is :venus
The value of the alternate is :earth
The last element is not getting stored in the arraylist.
Do not understand why? New to Java programming.
This section has a few problems also present throughout
AlternateNew.add(alternate[0]);
for(int i=1;i<keyword.length;i++){
if(keyword[i]==(keyword[i-1])){
AlternateNew.add(alternate[i]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
The naming convention in Java is to start with a lowercase letter for a variable name (unless it is a constant), which is why object AlternateNew is highlighted as if it were a class name.
The else if block tests the opposite of the same condition as its if. You could comment out if(!(keyword[i]==(keyword[i-1])), delete, or replace it with a more readable reminder comment, and the result would be the same.
AlternateNew.add(alternate[i]); happens regardless of this condition, in either branch of the if, so either remove the if statement entirely or fix some typo.
As for your actual [edit: original] question, I can't find anything wrong. Are you sure you didn't forget to save the csv file? I ran it using a text file and got output contrary to your post!