String index out of range

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 2111 Views - Last Post: 07 March 2011 - 05:44 PM Rate Topic: -----

#1 Ap0C552  Icon User is offline

  • D.I.C Regular

Reputation: -7
  • View blog
  • Posts: 314
  • Joined: 08-December 10

String index out of range

Posted 07 March 2011 - 01:30 PM

EDIT: edit added at bottom of post

I am using a substring method to break apart a line of text at each comma.

I am getting a String index out of range: -1 error but I can't figure out why.

Here is the complete code.

The specific area that is the problem is this one

token1=line.indexOf(",",token+1);
price=Integer.parseInt(line.substring(token+1,token1).trim());


A sample of the line of info it is reading is..

Quote

Walther p88 compact, 200, 1.45


import java.io.*;

public class WeaponsLoader{
	public static void main (String[]args)
	{

		Item[] weapons = weaponloader();

		System.out.println(weapons[10]);

    }
		public static Item[] weaponloader()

		{

			String line;
			Item[] weaponArray=new Item[42];
			int position=0;
			int arraySize;
			int token=0;
			int token1=0;

			String name;
			int price=0;
			double attack=0;

			try
			{

				FileReader fileIn=new FileReader("Weapons.txt");
				BufferedReader reader=new BufferedReader(fileIn);

				line=reader.readLine().trim();

				while(line!=null)
				{
					if(position>0)
					{
						if(position==1)
						{
							//arraySize=Integer.parseInt(line);

						}
						if(position>1)
						{
							token=line.indexOf(",");
							name=line.substring(0,token);

							token1=line.indexOf(",",token+1);
							price=Integer.parseInt(line.substring(token+1,token1).trim());

							attack=Double.parseDouble(line.substring(token1+1));

							Weapon current=new Weapon(name,price,attack);

							weaponArray[position-2]=current;
						}

					}

					line=reader.readLine().trim();
					position++;
				}
			}
			catch (IOException ioe)
			{
				System.out.println(ioe.getMessage());
				ioe.printStackTrace();
			}

			return weaponArray;
}

}




Thanks!

EDIT: I tested the same code in an isolated state and it worked fine just like this...

public class tester1{
	public static void main (String[]args)

	{

		String line="Walther p88 compact,200, 1.45";
        int token=0;
        int token1=0;

        String name="";
        double attack=0;
        int price=0;


		token=line.indexOf(",");
		System.out.println(token);
		name=line.substring(0,token);

		token1=line.indexOf(",",token+1);
		System.out.println(token1);
		price=Integer.parseInt(line.substring(token+1,token1).trim());

		attack=Double.parseDouble(line.substring(token1+1));

		System.out.println("Name:"+name+" Price:"+price+" Attack:"+attack);
	}
}

This post has been edited by Ap0C552: 07 March 2011 - 01:39 PM


Is This A Good Question/Topic? 0
  • +

Replies To: String index out of range

#2 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: String index out of range

Posted 07 March 2011 - 01:53 PM

Since indexOf take a char argument, try changing line 46 to
token=line.indexOf(',');
and also make the equivalent correction to line 49.
Was This Post Helpful? 0
  • +
  • -

#3 Ap0C552  Icon User is offline

  • D.I.C Regular

Reputation: -7
  • View blog
  • Posts: 314
  • Joined: 08-December 10

Re: String index out of range

Posted 07 March 2011 - 01:56 PM

Thanks for the input. It did not fix the problem.

I isolated the code that breaks up the string in a separate program, and it works perfectly fine. So I need to see exactly what the difference is in the larger program.

EDIT:

I used some diagnosing and confirmed that the piece of code that breaks up the string works fine.

It read through all valid lines, and once it reaches past the last line, it throws this error. I am confused since the loop is only supposed to run while the line does not equal null. Is there something wrong with my conditional in my while loop?

This post has been edited by Ap0C552: 07 March 2011 - 02:05 PM

Was This Post Helpful? 0
  • +
  • -

#4 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,682
  • Joined: 13-March 10

Re: String index out of range

Posted 07 March 2011 - 02:04 PM

check split() method.
Was This Post Helpful? 0
  • +
  • -

#5 Ap0C552  Icon User is offline

  • D.I.C Regular

Reputation: -7
  • View blog
  • Posts: 314
  • Joined: 08-December 10

Re: String index out of range

Posted 07 March 2011 - 02:12 PM

Split method might be better, but I have concluded that is irrelevant at this point, because the problem is that the loop is reading a line once the program get past the last valid line.......I have no clue why.
Was This Post Helpful? 0
  • +
  • -

#6 Ap0C552  Icon User is offline

  • D.I.C Regular

Reputation: -7
  • View blog
  • Posts: 314
  • Joined: 08-December 10

Re: String index out of range

Posted 07 March 2011 - 02:24 PM

I set the loop to print out the current line it is reading, and the conditional.

There are 43 lines in the file, yet it reads line 44 and the conditional is true. Makes no sense to me.

Here is the output

Quote

When reading line=0 The conditional is:true
When reading line=1 The conditional is:true
When reading line=2 The conditional is:true
When reading line=3 The conditional is:true
When reading line=4 The conditional is:true
When reading line=5 The conditional is:true
When reading line=6 The conditional is:true
When reading line=7 The conditional is:true
When reading line=8 The conditional is:true
When reading line=9 The conditional is:true
When reading line=10 The conditional is:true
When reading line=11 The conditional is:true
When reading line=12 The conditional is:true
When reading line=13 The conditional is:true
When reading line=14 The conditional is:true
When reading line=15 The conditional is:true
When reading line=16 The conditional is:true
When reading line=17 The conditional is:true
When reading line=18 The conditional is:true
When reading line=19 The conditional is:true
When reading line=20 The conditional is:true
When reading line=21 The conditional is:true
When reading line=22 The conditional is:true
When reading line=23 The conditional is:true
When reading line=24 The conditional is:true
When reading line=25 The conditional is:true
When reading line=26 The conditional is:true
When reading line=27 The conditional is:true
When reading line=28 The conditional is:true
When reading line=29 The conditional is:true
When reading line=30 The conditional is:true
When reading line=31 The conditional is:true
When reading line=32 The conditional is:true
When reading line=33 The conditional is:true
When reading line=34 The conditional is:true
When reading line=35 The conditional is:true
When reading line=36 The conditional is:true
When reading line=37 The conditional is:true
When reading line=38 The conditional is:true
When reading line=39 The conditional is:true
When reading line=40 The conditional is:true
When reading line=41 The conditional is:true
When reading line=42 The conditional is:true
When reading line=43 The conditional is:true
When reading line=44 The conditional is:true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1937)
at WeaponsLoader.weaponloader(WeaponsLoader.java:53)
at WeaponsLoader.main(WeaponsLoader.java:7)
Press any key to continue . . .

Was This Post Helpful? 0
  • +
  • -

#7 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: String index out of range

Posted 07 March 2011 - 03:04 PM

please post your current code and the data file.
Was This Post Helpful? 0
  • +
  • -

#8 Ap0C552  Icon User is offline

  • D.I.C Regular

Reputation: -7
  • View blog
  • Posts: 314
  • Joined: 08-December 10

Re: String index out of range

Posted 07 March 2011 - 03:48 PM

Current Code

import java.io.*;

public class WeaponsLoader{
	public static void main (String[]args)
	{

		Item[] weapons = weaponloader();

		System.out.println(weapons[10]);

    }
		public static Item[] weaponloader()

		{

			String line;
			Item[] weaponArray=new Item[42];
			int position=0;
			int arraySize;
			int token=0;
			int token1=0;

			String name;
			int price=0;
			double attack=0;

			try
			{

				FileReader fileIn=new FileReader("Weapons.txt");
				BufferedReader reader=new BufferedReader(fileIn);

				line=reader.readLine().trim();

				boolean check;

				while(line!=null)
				{

					check=(line!=null);
					System.out.println("When reading line="+position+" The conditional is:"+check);

					if(position>0)
					{
						if(position==1)
						{
							//arraySize=Integer.parseInt(line);

						}
						if(position>1&&line!=null)
						{
							token=line.indexOf(',');
							name=line.substring(0,token);

							token1=line.indexOf(',',token+1);
							price=Integer.parseInt(line.substring(token+1,token1).trim());

							attack=Double.parseDouble(line.substring(token1+1).trim());

							Weapon current=new Weapon(name,price,attack);

							weaponArray[position-2]=current;
						}

					}

					line=reader.readLine();
					position++;
				}
			}
			catch (IOException ioe)
			{
				System.out.println(ioe.getMessage());
				ioe.printStackTrace();
			}

			return weaponArray;
}

}







The data file is named Weapons.txt and contains info in this format

//THE FIRST LINE MUST BE THE HEADER THE SECOND LINE MUST BE THE NUMBER OF WEAPONS - FORMAT=(name,price,attack)
42
Walther p88 compact, 200, 1.45
Berreta .22, 200, 1.45
Sig Sauer P220 Combat, 200, 1.45 
SIG 229 .357, 200, 1.45
Ruger LCP, 400, 1.45
Smith & Wesson .45, 400, 1.45
Browning 9x19mm Hi-Power, 400, 1.45
Carbon 15, 400, 1.45
Heckler & Koch MK23 Mod 0, 800, 1.45
Glock 31 .357 sig, 800, 1.45
Desert Eagle .44 cal, 800, 1.45
Ruger p90 .45, 800 , 1.45
Glock 39 .45 GAP, 1600, 1.45
Desert Eagle .50 cal, 1600, 1.45
Mac 10 machine pistol, 1600 , 1.45
Taurus 4/10 revolver, 1600, 1.45
M3 "Grease Gun" submachine gun, 4000, 1.45
Thompson submachine gun, 4000 , 1.45
Colt 9mm SMG submachine gun, 4000, 1.45
calico m960 submachine gun, 4000, 1.45
H&K Mp5 SMG submachine gun, 8000, 1.45
H&k Mp7 SMG submachine gun, 8000, 1.45
H&K UMP submachine gun, 8000, 1.45
Steyr TMP submachine gun, 8000, 1.45
TDI Vector submachine gun, 16000, 1.45
IMI Galil assault rifle, 16000, 1.45
FAMAS assault rifle, 16000, 1.45
AK-47 assault rifle, 16000, 1.45
Steyr AUG assault rifle,20000 , 1.45
M4 Carbine assault rifle, 20000 , 1.45
H&K G36 assault rifle, 20000 , 1.45
SIG SG 550 assault rifle, 20000, 1.45 
FN f2000 assault rifle, 30000, 1.45
FN scar assault rifle, 30000, 1.45
Bren machine gun, 30000, 1.45
RPK machine gun, 30000, 1.45
M60 machine gun, 35000, 1.45
M2 Browning machine gun, 40000, 1.45
FN Minimi machine gun, 40000, 1.45
Rocket-propelled grenade launcher, 40000, 1.45 
bazooka, 40000, 1.45
AGS-17 grenade launcher, 50000, 1.45










This post has been edited by Ap0C552: 07 March 2011 - 03:56 PM

Was This Post Helpful? 0
  • +
  • -

#9 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: String index out of range

Posted 07 March 2011 - 04:01 PM

I see 44 lines:
a comment
an int
42 lines of strings

(but that still doesn't explain the problem).

This post has been edited by r.stiltskin: 07 March 2011 - 04:04 PM

Was This Post Helpful? 0
  • +
  • -

#10 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,464
  • Joined: 27-December 08

Re: String index out of range

Posted 07 March 2011 - 04:05 PM

Obviously this line token=line.indexOf(','); returns -1 for token. Really, split() isn't irrelevant and would make things a whole lot easier:
String s = reader.readLine(); //read the line
String[] tokens = s.split(","); //split it on the comma

//if there are three tokens (or two commas)
//then create a Weapon from those elements
if(tokens.length == 3){
     items[position++] = new Weapon(tokens[0], 
                                    Integer.parseInt(tokens[1]), 
                                    Double.parseDouble(tokens[2]));
}


Was This Post Helpful? 0
  • +
  • -

#11 Ap0C552  Icon User is offline

  • D.I.C Regular

Reputation: -7
  • View blog
  • Posts: 314
  • Joined: 08-December 10

Re: String index out of range

Posted 07 March 2011 - 04:25 PM

I replaced the code with the split method. But like I mentioned earlier that is not the problem. The loop keep on running past any valid lines.

All of this is in a while loop that use the conditional

while(line!=null)


So for some reason the blank line is not returning a null when it is read.
Was This Post Helpful? 0
  • +
  • -

#12 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: String index out of range

Posted 07 March 2011 - 04:27 PM

View Postmacosxnerd101, on 07 March 2011 - 06:05 PM, said:

Obviously this line token=line.indexOf(','); returns -1 for token.

What do you mean???

That's not obvious to me. It returns the position of the comma in each line.
Was This Post Helpful? 0
  • +
  • -

#13 Ap0C552  Icon User is offline

  • D.I.C Regular

Reputation: -7
  • View blog
  • Posts: 314
  • Joined: 08-December 10

Re: String index out of range

Posted 07 March 2011 - 04:32 PM

Problem solved.

At the end of the text file there were a bunch of blank line where I guess I had press enter and made space. While it did not consider these lines null even though there was no text there.

This is odd because while(line!=null) is the way we were taught in class to do it, yet it so easily falls error.

I changed the conditional to
while(line.length()>0);

Was This Post Helpful? 0
  • +
  • -

#14 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: String index out of range

Posted 07 March 2011 - 04:35 PM

I modified your code slightly, replacing Item with Object so I could compile & run it. It runs correctly, unless I add a spurious extra line containing a blank space at the end of the data file. That's the only way I was able to reproduce your error. So I suggest you examine the data file closely to see if there's anything following the final weapon entry.


edit: Ha, ha. Right answer, a minute too late.

This post has been edited by r.stiltskin: 07 March 2011 - 04:36 PM

Was This Post Helpful? 0
  • +
  • -

#15 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: String index out of range

Posted 07 March 2011 - 04:52 PM

View PostAp0C552, on 07 March 2011 - 06:32 PM, said:

While it did not consider these lines null even though there was no text there.

The problem is that there isn't "no text there". There are, at the very least, newline characters there. Whitespace is still text.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2