Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Reading from a text file. Help needed urgently.

  1. #1
    Junior Member
    Join Date
    Dec 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default [Solved]Reading from a text file. Help needed urgently.

    Hello! I'm working on a Java project due Wednesday. My partner and I are having a ton of trouble with one bit of our program. We have a Scanner object called "fileInput" that we're using to read from a text file. The format of the text file is as follows:

    1
    8
    5
    5
    n 3,n 4,p 3,n 4,x 0
    x 0,p 3,p 8,x 0,x 0
    x 0,x 0,x 0,x 0,x 0
    p 8,x 0,x 0,x 0,x 0
    p 6,n 1,x 0,x 0,x 0

    The first 4 numbers have given us no troubles, but in case you must know the first is the max amount of cycles iterated through in this "game" we're making (not relevant here), the second is another gameplay-related item, and the following two are height and width of the grid below. It's the grid below that's causing problems. We want to create a 2D array of "Cell" objects containing a number of either pirates, ninjas, or neither (yes, that's part of the assignment, and yes, it's silly). Commas are separators between Cells. Naturally, "n 3" means "put three ninjas in this spot," and p stands for pirates, and x means "nothing is here."

    Here's the code snippet that reads in the file. "inputFileName" is a string representing the name of the file. As you can see, we start out with a few "<arbitrary variable> = fileInput.nextInt();" lines. All seems well, upon debugging these values appear to be stored properly and presumably passed into the Arena object constructor below.

    However, two major problems surface right away.

    First, I get this exception:
    [COLOR="Red"]Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
    	at java.lang.String.substring(Unknown Source)
    	at java.lang.String.substring(Unknown Source)
    	at BattleRoyale.main(BattleRoyale.java:77)[/COLOR]

    I'll mark line 77 with a comment in the code snippet below and bold it, so you can tell where it crashes. I'm also worried about the fact that changing the string index, which is a positive number, changes the "out of range" index to the equivalent negative number. If I try "splitLine[i].substring(1)" I get "String index out of range: -1" and likewise with three. Four may or may not exist, depending on whether the number of pirates or ninjas in the given

    The other problem is that, when I set breakpoints and run through with debug, "line" and "splitLine" never seem to contain anything but empty strings, or "". Not what I wanted. Does it have anything to do with the fact that strings are reference variables in Java? Regardless, I bolded the relevant lines as well.

    try
    	    {
    			Scanner fileInput = new Scanner(new FileReader(inputFileName));
     
    			try
    			{
    				int maxTicks = fileInput.nextInt();
    				int rovingBand = fileInput.nextInt();
    				int height = fileInput.nextInt();
    				int width = fileInput.nextInt();
    				Cell[][] initialGrid = new Cell[height][width];
     
    				[B]int gridLine = 0;
    				String line;
    				String[] splitLine;[/B]
     
    				while (fileInput.hasNextLine())
    				{
    					[B]line = fileInput.nextLine();
    					splitLine = line.split(",");
    					int amount = 0;[/B]
     
    					for (int i = 0; i < splitLine.length; i++)
    					{
    						try
    						{
    							[B]amount = Integer.parseInt( splitLine[i].substring(2) ); //Line 77[/B]
    						}
    						catch (NumberFormatException e)
    						{
    							System.out.println("Something went wrong: Input file grid contains invalid data.");
    							showHelpAndExit(); //refers to a private method not in this snippet, self-explanatory
    						}
     
    						switch (splitLine[i].charAt(0))
    						{
    						case 'n':
    							initialGrid[gridLine][i] = new Cell(amount, 0); //first argument is number of ninjas, second is number of pirates
    							break;
    						case 'p':
    							initialGrid[gridLine][i] = new Cell(0, amount);
    							break;
    						case 'x':
    							initialGrid[gridLine][i] = new Cell(); //no arguments mean set both pirates and ninjas to zero
    							break;
    						default:
    							System.out.println("Something went wrong: Invalid character found for cell pirate/ninja identifier.");
    							showHelpAndExit();
    						}
     
    					}
     
    					gridLine++; //allows vertical iteration through grid
     
    				}
     
    				arena = new Arena(maxTicks,
    						rovingBand,
    						height,
    						width,
    						initialGrid,
    						random);
     
    			}
    			catch (InputMismatchException e)
    			{
    				System.out.println("Something went wrong: A string was used where an integer should have been found, or vice versa. Also, floating-point numbers may have been used.");
    				showHelpAndExit();
    			}
     
    			fileInput.close();
    		}
    		catch (FileNotFoundException e)
    		{
    			System.out.println("Input file not found. Ensure that the file is in the current directory, is spelled correctly, includes the file extension, and that it actually exists.");
    			System.exit(1);
    		}
     
    	}

    The majority of this code is only included for contextual purposes. The bolded parts are what I am having trouble with. I need to figure this out quickly, as the project is due Wednesday and we cannot continue the project without knowing how to figure this out. So would a kind person be willing to help me out? If you need information or clarification, let me know.

    Also, if by any chance you're curious about the project itself, here is the page complete with instructions:

    CS302: Program 4
    Last edited by TheAirPump; December 14th, 2009 at 06:17 PM. Reason: Solved.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Reading from a text file. Help needed urgently.

    The nextInt function includes the next int (not the line) so as you read your the fourth Int, the call to nextLine will return an empty string. Instead of calling nextInt for the first four lines, just call nextLine().

  3. #3
    Junior Member
    Join Date
    Dec 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a text file. Help needed urgently.

    Quote Originally Posted by copeg View Post
    The nextInt function includes the next int (not the line) so as you read your the fourth Int, the call to nextLine will return an empty string. Instead of calling nextInt for the first four lines, just call nextLine().
    Oh, thank you! Of course, being too quick to jump to conclusions about how stuck I am, I figured it out within the next hour or two. Thanks anyway, though.

Similar Threads

  1. Reading doubles from file
    By fawx in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: October 24th, 2009, 11:57 PM
  2. [SOLVED] File Reading from the specified location
    By rajesh.mv in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: August 13th, 2009, 12:56 AM
  3. Problem on reading file in Java program
    By nathanernest in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: April 13th, 2009, 08:14 AM
  4. [SOLVED] Program to read from created file
    By aznprdgy in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 7th, 2009, 03:51 AM
  5. [SOLVED] Problem in reading a file from java class
    By aznprdgy in forum File I/O & Other I/O Streams
    Replies: 11
    Last Post: March 23rd, 2009, 09:31 AM