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 11 of 11

Thread: Very strange results when reading from a test file

  1. #1
    Junior Member
    Join Date
    Sep 2011
    Posts
    24
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Very strange results when reading from a test file

    I am trying to write a program that will read a text file, write its relavent contents into an array, then produce an output based on the data. I structured the data files like this: (note, parentheses represent brackets, and the form is (blocktype)(x)(y))
    (Castle File)
     
    BEGIN ROW 1
    (1)(-50)(-50)
    (1)(-40)(-50)
    (2)(-30(-50)

    This is the code used to read the files:

     
    	public static int[][] readFile(String filename){
    	    int[][] blocks = new int[1028][3];
    	    try {
       			BufferedReader in = new BufferedReader(new FileReader(filename));
        		String str;
        		int count = 0;
        		int written = 0;
        		while ((str = in.readLine()) != null) {
        			if (written > 0){
        				count ++;
        			}
        			written = 0;
            		char[] temp = str.toCharArray();		// creates an array to hold data from current line
            		int i = 0;
            		int rnum;
            		int num = 0;
            		boolean reading = false;
            		boolean negative = false;
            		int c = 0;
            		int d = 0;
            		while (i < temp.length){
            			if (temp[i] == '['){
            				reading = true;
            				i ++;
            			}
            			if (temp[i] == ']'){
            				reading = false;
            				d = 0;
            				if (negative){
            					num *= -1;
            					negative = false;			// checks for end bracket and updates the current
            				}								// variable with the information held in num
            				blocks[count][c] = num / 10;
            				c ++;
            				num = 0;
            				written ++;;
            			}
            			if (reading){
            				if (temp[i] == '-'){
            					negative = true;
            				}
            				else{
            					rnum = temp[i] - 48;
            					num += rnum * sq(10, d);	// adds next character to the current number
            					if (rnum == 0){
            						num *= 10;
            					}
            					d ++;
            				}
            			}
            			i ++;
            		}
            		blocks[0][0] = count;
        		}
        	in.close();
    		} catch (IOException e) {
    		}
     
    		return blocks;
    	}
     
    	public static int sq(int a, int b){
    		int i = 1;
    		int sum = a;
    		while (i < b){
    			sum *= a;
    			i ++;
    		}
    		if (b == 1){
    			sum = 1;
    		}
    		return sum;
    	}
     
    	public static void drawCastle(SketchPad p, int[][] blocks){
    		int i = 1;
    		while (i <= blocks[0][0]){
    			if (blocks[i][0] == 1){
    				drawBrick(p, blocks[i][1], blocks[i][2], 20, 10);
    			}
    			if (blocks[i][0] == 2){
    				drawBrick(p, blocks[i][1], blocks[i][2], 10, 10);
    			}
    			if (blocks[i][0] == 3){
    				drawWindow(p, blocks[i][1], blocks[i][2], 30, 30);
    			}
    			if (blocks[i][0] == 4){
    				drawDoor(p, blocks[i][1], blocks[i][2], 40, 60);
    			}
    			i++;
    			System.out.println(blocks[i][0] + " " + blocks[i][1] + " " + blocks[i][2]);
    		}
    	}
    }

    These are he issues I am having:
    1. for some reason, I must include some statement in brackets at the beginning of the file, otherwise my first 2 data entries aren't read.

    2. for some reason, Whenever there is an empty line, I must have a line of non-bracketed data before any real data. Neither this, nor issue number 1 was part of any intentional design

    3. When values over 100 are entered, the program displays the following behavior:

    if value is evenly divisible by 100 (200, 300, 400 etc.) then it works fine

    if the value is evenly divisible by 10, but not 100 (130, 140, 150 etc.) then it drops the final zero resulting in 13, 14, 15

    if the value is of the form (intger)(integer)(integer) then the middle integer is dropped

    if the value is of the form (intger)(zero)(intger) then the middle value is dropped and the final value is incremented by one (integer)(integer + 1)

    NOTE: the above conditions only apply to the second value (the x value), all other values work fine


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Very strange results when reading from a test file

    Sounds like you have a logic error in your parsing logic.
    Try debugging your code by adding printlns to show the values of variables as they change.
    Print out everything that you use to make a decision so you can see what the values are as they change. Since you know what you want your code to do, if you see values that are not correct, you should be able to fix the logic to make the values what you want them to be.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Very strange results when reading from a test file

    Given this in the input file what is supposed to go into the two dim int array?
    (Castle File)

    BEGIN ROW 1
    (1)(-50)(-50)
    (1)(-40)(-50)
    (2)(-30(-50) <<<<<<<<<<< missing ) here?

  4. #4
    Junior Member
    Join Date
    Sep 2011
    Posts
    24
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very strange results when reading from a test file

    The desired 2dimensional array would be this:

     
    blocks[1][0] = 1
    blocks[1][1] = -50
    blocks[1][2] = -50
     
    blocks[2][0] = 1
    blocks[2][1] = -40
    blocks[2][1] = -50
     
    blocks[3][0] = 2
    blocks[3][1] = -30
    blocks[3][2] = -50

    yes there was a missing paren

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Very strange results when reading from a test file

    Here's a suggestion for testing that allows everyone to use the same data. Put the input into the program:
     
           final String Data = "(1)(-50)(-50)\n(1)(-40)(-50)\n(2)(-30)(-50)\n";   //For testing<<<<<<<<<<
           CharArrayReader car = new CharArrayReader(Data.toCharArray());
     
    	    try {
       		BufferedReader in = new BufferedReader(car); //new FileReader(filename));

    What goes in the first row of the array: block[0] ???
    Last edited by Norm; September 11th, 2011 at 11:03 AM.

  6. #6
    Junior Member
    Join Date
    Sep 2011
    Posts
    24
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very strange results when reading from a test file

    Again, I don't know why, but it is leaving the first row blank, so I am manually assigning the first spot to hold the total number of blocks.

    Also, is it possible to create a String from an array of chars? If so, I could solve my parsing problem by creating a string out of everything inside of the brackets, and then converting it to an integer, then adding it to the blocks array.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Very strange results when reading from a test file

    it is leaving the first row blank
    Not when I execute the program. I get the following output:
    The input:
    (1)(-50)(-50)
    (1)(-400)(-50)
    (2)(-30)(-500)

    blocks[0]=[2, -50, -50] <<<<<<<< Here 0,0 is overwritten by blocks[0][0] = count;
    blocks[1]=[1, -400, -50]
    blocks[2]=[2, -30, -500]

    0 error(s)

  8. #8
    Junior Member
    Join Date
    Sep 2011
    Posts
    24
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very strange results when reading from a test file

    Ok, I know what's causing that now, the original problem was coming because of an error in the code that was corrected later.

    Also, I found the root of all my other problems.

    rnum = temp[i] - 48;
    num += rnum * sq(10, d);	// this line is the problem
    if (rnum == 0){
    num *= 10;
    }
    d ++;

    My problem was that when I was parsing the int, I was reading it from left to right instead of right to left, with a special condition for zeros. So the first number would be read at its face value (not adjusted for position) and all subsequent values in the nth place would be read at n * 10^n. Instead of trying to correct the algorithm to read it the correct way, I just added the characters that needed to be read to a String, and then called Integer.parseInt(string).

    corrected code:

    /**
     * @(#)Castle.java
     *
     * Castle application
     *
     * @author
     * @version 1.00 2011/9/9
     */
    import apcslib.*;
    import java.awt.*;
    import java.awt.Color;
    import java.util.*;
    import java.io.*;
     
    public class Castle {
     
    //======= Main Method =============================
     
        public static void main(String[] args) {
     
    //======= Variable Initialization =================
        	DrawingTool pencil;
        	SketchPad paper = new SketchPad(500, 500);
       		pencil = new DrawingTool(paper);
       		Scanner input = new Scanner(System.in);
    //=================================================
     
    		System.out.println("enter file path:");			// gets file path from the user
    		String path = input.nextLine();
     
       		int[][] blocks = readFile(path);				// reads file data into blocks array
     
       		drawCastle(paper, blocks);						// displays information held in file
     
        }
    //=================================================
     
    //======= Brick Drawing Method ====================
    // REQUIRES: java.awt.Color, SketchPad, DrawingTool
    // AUTHOR: Nicky DiCarlo
     
        public static SketchPad drawBrick(SketchPad p, double x, double y, double width, double height){
        	DrawingTool g = new DrawingTool(p);
        	Color gray = new Color(100,100,100);
      		g.up();
       		g.move(x + (width / 2), y - (height / 2));		// moves to center of the rectangle
      		g.down();
      		g.drawRect(width, height);
      		g.setColor(gray);
      		g.move(x + (width / 2), y - (height / 2) - 1);	// moves to adjusted center and fills in brick
      		g.fillRect(width - 1, height - 1);
      		g.setColor(Color.black);
      		return p;
        }
     
    //=================================================
     
    //======= Door Drawing Method =====================
    // REQUIRES: java.awt.Color, SketchPad, DrawingTool
    // AUTHOR: Nicky DiCarlo
     
        public static SketchPad drawDoor(SketchPad p, double x, double y, double width, double height){
        	DrawingTool g = new DrawingTool(p);
        	Color brown = new Color(139,69,19);
      		g.up();
       		g.move(x + (width / 2), y - (height / 2));		// moves to center of the door
      		g.down();
      		g.drawRect(width, height);						// draws frame
      		g.setColor(brown);
      		g.move(x + (width / 2), y - (height / 2) - 1);	// fills in door with brown
      		g.fillRect(width - 1, height - 1);
      		g.move(x + (width * .75), y - height / 2);
      		g.setColor(Color.yellow);
      		g.fillOval((width / 6), (width / 6));			// creates doorknob
      		g.setColor(Color.black);
      		return p;
        }
     
    //=================================================
     
        public static SketchPad drawWindow(SketchPad p, double x, double y, double width, double height){
        	DrawingTool g = new DrawingTool(p);
        	Color brown = new Color(139, 69, 19);
        	g.up();
        	g.move(x + width / 2, y - height / 2);
        	g.down();
        	g.drawRect(width / 6, height);					// moves to center of pane and draws framess
        	g.drawRect(width, width / 6);
        	g.setColor(brown);
        	g.fillRect((width) - 1, (height) / 6 - 1);		// adjusts center and fills in frames
        	g.move(x + (width / 2) + 1, y - (height / 2) - 1);
        	g.fillRect((width) / 6 - 1, height - 1);
      		g.setColor(Color.black);
      		return p;
        }
     
    	public static int[][] readFile(String filename){
    	    int[][] blocks = new int[1028][3];
    	    try {
       			BufferedReader in = new BufferedReader(new FileReader(filename));
        		String str;
        		int count = 0;
        		int written = 0;
        		String number = "";
        		while ((str = in.readLine()) != null) {
        			if (written > 0){
        				count ++;
        			}
        			written = 0;
            		char[] temp = str.toCharArray();		// creates an array to hold data from current line
            		int i = 0;
            		int ri = 0;
            		boolean reading = false;
            		boolean negative = false;
            		int c = 0;
            		int d = 0;
            		while (i < temp.length){
            			if (temp[i] == '['){
            				reading = true;
            				i ++;
            			}
            			if (temp[i] == ']'){
            				reading = false;
            				int tempint = Integer.parseInt(number);
            				blocks[count][c] = tempint;
            				c ++;
            				System.out.println(number);
            				number = "";
            				written ++;;
            			}
            			if (reading){
            				number += temp[i];
            			}
            			i ++;
            		}
            		blocks[0][0] = count;
        		}
        	in.close();
    		} catch (IOException e) {
    		}
     
    		return blocks;
    	}
     
    	public static void drawCastle(SketchPad p, int[][] blocks){
    		int i = 1;
    		while (i <= blocks[0][0]){
    			if (blocks[i][0] == 1){
    				drawBrick(p, blocks[i][1], blocks[i][2], 20, 10);
    			}
    			if (blocks[i][0] == 2){
    				drawBrick(p, blocks[i][1], blocks[i][2], 10, 10);
    			}
    			if (blocks[i][0] == 3){
    				drawWindow(p, blocks[i][1], blocks[i][2], 30, 30);
    			}
    			if (blocks[i][0] == 4){
    				drawDoor(p, blocks[i][1], blocks[i][2], 40, 60);
    			}
    			i++;
    			System.out.println(blocks[i][0] + " " + blocks[i][1] + " " + blocks[i][2]);
    		}
    	}
    }

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Very strange results when reading from a test file

    Why are you parsing the input byte by byte? There are other ways to split the input and convert from String to integer.

  10. #10
    Junior Member
    Join Date
    Sep 2011
    Posts
    24
    My Mood
    Mellow
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very strange results when reading from a test file

    I wasn't aware of a better way to check for integers only within brackets, and I already had some code left over from a previous project where I checked for text tags within brackets, so I applied it to this, I just constructed my integers incorrectly. How would you have parsed this?

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Very strange results when reading from a test file

    Either indexOf and substring
    or split

    Then Integer parseInt

Similar Threads

  1. [SOLVED] Issues with a test driver file
    By Gthoma2 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: July 18th, 2011, 07:54 PM
  2. Reading from a file
    By NeedzABetterSN in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 5th, 2011, 08:07 AM
  3. Reading a file
    By Soccer13 in forum Java Theory & Questions
    Replies: 2
    Last Post: October 26th, 2010, 08:55 PM
  4. Anyone Help me in XML file Reading??????????
    By goplrao in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: May 2nd, 2010, 11:04 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

Tags for this Thread