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: .txt file won't convert to ints

  1. #1
    Junior Member
    Join Date
    May 2022
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default .txt file won't convert to ints

    Heya! I'm having trouble converting a .txt file to ints and storing them in an array. All variables not seen have been properly initialized. Initially, I was getting an error message similar to the one below, but instead, it was the � (unidentified character) you see in one of the .replaceAll statements. I think the issue is happening during the code's attempt at parsing the string, and for some reason, it's saying that the null space can't be converted into an int, when it should just skip over it (it's not even a space, it's just null). Any clue as to what I should do would be greatly appreciated. Thanks!


    Here's the error:

    Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(Num berFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:646)
    at java.base/java.lang.Integer.parseInt(Integer.java:778)
    at tile.TileManager.loadMap(TileManager.java:86)
    at tile.TileManager.<init>(TileManager.java:30)
    at main.GamePanel.<init>(GamePanel.java:41)
    at main.Main.main(Main.java:20)


    "at tile.TileManager.loadMap(TileManager.java:86)" is referencing this line:

    nums[col] = Integer.parseInt(String.valueOf(line.charAt(col))) ;

    Anything errors below this one are irrelevant, as it's just tracing how the class got called.



    public void loadMap() {
     
    		//try {
    			InputStream is = getClass().getResourceAsStream("/maps/map0001.txt"); //imports the text file
    			Scanner scnr = new Scanner(is); //lets us read the contents of the text file
     
    			int col = 0;
    			int row = 0;
     
     
    			while(row < gp.maxScreenRow) { //loops through all rows coordinates
     
     
    				while(scnr.hasNextLine()) { //checks if the scanner has anything to read, if so, it reads that line, stores it in mapTileNum and increments row
     
     
    					String line = scnr.nextLine();//stores a scanned line in the String "line"
    					line = line.replaceAll(" ","");//removes all spaces
    					line = line.replaceAll("�","");//removes all unknown characters
    					if(line.equals("")) {
    						continue;
    					}
    					//String[] numbers = new String[gp.maxScreenCol];//creates a new String array that will store all of the numbers in a given row
    					int[] nums = new int[gp.maxScreenCol];//all of the Strings in numbers will be converted to ints and stored here
     
     
    					while(col < line.length()) {//goes through all characters (actually numbers, not yet parsed) of line
     
     
     
    						nums[col] = Integer.parseInt(String.valueOf(line.charAt(col))); //uses col to get a specific value from the map, and .parseInt changes it from a string to an Integer
     
    						mapTileNum[col][row] = nums[col]; //stores the extracted value in the equivalent place in a 2d array
    						col++;
     
    					}
     
    					/*for(int i = 0; i < numbers.length; i++) {
    					String replacement = numbers[i].replace(" ", "");
    					numbers[i] = replacement;
    					}*/
     
    					row++;
    				}
     
    			}
     
    			scnr.close();
    		/*}catch(IOException e) {
    			e.printStackTrace();
    		}*/
    	}
    Last edited by Haminaya; May 31st, 2022 at 08:48 PM.

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

    Default Re: .txt file won't convert to ints

    Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(Num berFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:646)
    at java.base/java.lang.Integer.parseInt(Integer.java:778)
    at tile.TileManager.loadMap(TileManager.java:86)
    at tile.TileManager.<init>(TileManager.java:30)
    at main.GamePanel.<init>(GamePanel.java:41)
    at main.Main.main(Main.java:20)


    "at tile.TileManager.loadMap(TileManager.java:86)" is referencing this line:

    nums[col] = Integer.parseInt(String.valueOf(line.charAt(col))) ;
    What are the values in the variables used in line 86? What is in line and what is in col?
    Add a print statement before line 86 that prints out those two variables' values.

    The error message says an empty String was passed to the parseInt method.
    Is the text of that message correct? Was there a space between the ""s?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    May 2022
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: .txt file won't convert to ints

    col increments with each time the code loops, and when it reaches a value of 16 (checked through col<line.length()), it increments the value of row. It keeps doing this until row is 9 or more (checked through row<gp.maxScreenRow)

    I added a "System.out.println(col + " " + row);", and it showed 1 0 right as the error popped up.

    I don't know where the "" is popping up in the code. It isn't a " ", it's a null value. Maybe the scanner is reading one too many lines? If so, how do I fix that?

    Thanks again.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: .txt file won't convert to ints

    Did you print out the values of line and col as I suggested?
    What was printed?

    it's a null value.
    Note: a null value is NOT the same as an empty String: ""
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    May 2022
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: .txt file won't convert to ints

    col printed out as 1, and the string was "1111111111111111" (which it was supposed to be). So it's having the issue where it's saying the first index is an empty string, even though it isn't.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: .txt file won't convert to ints

    Where is the col=0 value printed? What was the value in line?
    Add this statement to the code after the statement that assigns a value to line:
       System.out.println("col="+ col + ", line=" + line + "<");
    Also print out the value of num[col] after the assignment statement that gives it a value is executed.

    Can you add the print statements, compile and execute the code, copy the print out and paste it here?

    Also post the code with the print statements so I can see where they are located.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    May 2022
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: .txt file won't convert to ints

    The output is:


    col=0, line before .replaceAll=��1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1<
    Exception in thread "main" col=0, line after .replaceAll=1111111111111111<
    47
    0
    0
    java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(Num berFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:646)
    at java.base/java.lang.Integer.parseInt(Integer.java:778)
    at tile.TileManager.loadMap(TileManager.java:106)
    at tile.TileManager.<init>(TileManager.java:30)
    at main.GamePanel.<init>(GamePanel.java:41)
    at main.Main.main(Main.java:20)



    Line 106 is still "nums[col] = Integer.parseInt(String.valueOf(line.charAt(col))) ;"

    public void loadMap() {
     
    		//try {
    			InputStream is = getClass().getResourceAsStream("/maps/map0001.txt"); //imports the text file
    			Scanner scnr = new Scanner(is); //lets us read the contents of the text file
     
    			int col = 0;
    			int row = 0;
     
     
    			while(row < gp.maxScreenRow) { //loops through all rows coordinates
     
     
    				while(scnr.hasNextLine()) { //checks if the scanner has anything to read, if so, it reads that line, stores it in mapTileNum and increments row
     
     
    					String line = scnr.nextLine();//stores a scanned line in the String "line"
     
     
    					System.out.println("col="+ col + ", line before=" + line + "<");//prints out the value of col & line before replacing the unwanted values
     
     
     
    					line = line.replaceAll(" ","");//removes all spaces
    					line = line.replaceAll("�","");//removes all unknown characters
     
     
     
    					System.out.println("col="+ col + ", line after=" + line + "<");//prints out the value of col & line before replacing the unwanted values
    					System.out.println(line.length());//prints out the length of line
     
     
     
    					if(line.equals("")) {
    						continue;
    					}
    					//String[] numbers = new String[gp.maxScreenCol];//creates a new String array that will store all of the numbers in a given row
    					int[] nums = new int[gp.maxScreenCol];//all of the Strings in numbers will be converted to ints and stored here
     
     
    					while(col < line.length()) {//goes through all characters (actually numbers, not yet parsed) of line
     
    						//System.out.println(col + " " + row);
    						//System.out.println(line);
     
     
    						System.out.println(nums[col]);
     
     
     
    						nums[col] = Integer.parseInt(String.valueOf(line.charAt(col))); //uses col to get a specific value from the map, and .parseInt changes it from a string to an Integer
     
    						mapTileNum[col][row] = nums[col]; //stores the extracted value in the equivalent place in a 2d array
    						col++;
     
    					}
     
    					/*for(int i = 0; i < numbers.length; i++) {
    					String replacement = numbers[i].replace(" ", "");
    					numbers[i] = replacement;
    					}*/
     
    					row++;
    				}
     
    			}
     
    			scnr.close();
    		/*}catch(IOException e) {
    			e.printStackTrace();
    		}*/
    	}

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: .txt file won't convert to ints

    What are these values shown in the printout?
    47
    0
    0
    The print statement should have a small String before the value that is printed so you know what it is the value of. Like you did here:
    System.out.println("col="+ col + ...

    The following ordering of the print statements would be better:
    				       System.out.println("line="+line);
     
     
    					while(col < line.length()) {//goes through all characters (actually numbers, not yet parsed) of line
     
    						System.out.println("col="+col + ", char=" + line.charAt(col));
     						nums[col] = Integer.parseInt(String.valueOf(line.charAt(col))); //uses col to get a specific value from the map, and .parseInt changes it from a string to an Integer
     
     						System.out.println("nums[col]=" + nums[col]);  // show after value assigned
     
    						mapTileNum[col][row] = nums[col]; //stores the extracted value in the equivalent place in a 2d array
    						col++;
     
    					}

    Also many of the comments in the code are too long and are not needed.
    For example the comment on this line is not needed; the code is self explanatory
    x = x + 2; // add 2 to x
    However this comment would be better, it says why the 2 is being added:
    x = x + 2; // Skip over 1 element in the array

    --- Update ---

    Why is this text:
    Exception in thread "main"
    before the col=0
    and not before
    java.lang.NumberFormatException: For input string: ""


    --- Update ---

    The purpose of the printouts is to see if any of the text is being parsed to an int.
    col starts at 0 and then increments. Does it ever get to 1?
    What is stored in the nums array? Its initial value is 0.
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: .txt file won't convert to ints

    Does the input txt file use UTF16 encoding?
    If so, the constructor for the Scanner class needs to be told that:
          Scanner scnr = new Scanner(is, "UTF16");                 //<<<<<<< needs charset Name
    If you don't understand my answer, don't ignore it, ask a question.

  10. The Following User Says Thank You to Norm For This Useful Post:

    Haminaya (May 31st, 2022)

  11. #10
    Junior Member
    Join Date
    May 2022
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: .txt file won't convert to ints

    It was the UTF16 encoding! Thank you so much! I've toiled at this for the past week and haven't gotten any further. Much appreciated.

  12. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: .txt file won't convert to ints

    The byte pattern in the before printout:
    line before .replaceAll=��1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1<
    shows two ? at the start of the line followed by alternating chars and "spaces".
    I recognize this as the pattern for a UTF16 file.

    Here is the printout as bytes of a UTF16 file. Notice the first two bytes are not ASCII characters
    and that following those 2 bytes are 2 byte pairs of ASCII values and 0s. See doc for UTF16
    The file contains the String "1234" '1' has an int value of 49
          System.out.println((int)'1'); //  49
     
          InputStream is = new FileInputStream(new File("TestUTF16.txt"));
          byte[] bytes = new byte[10];   // read first 10 bytes of file here
          is.read(bytes);
          is.close();
          System.out.println(Arrays.toString(bytes));  // [-1, -2, 49, 0, 50, 0, 51, 0, 52, 0]
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. How to convert text file to xml file with DOM parser?
    By veryoldgd in forum Java SE APIs
    Replies: 0
    Last Post: September 9th, 2014, 07:28 AM
  2. Replies: 1
    Last Post: August 19th, 2014, 12:12 PM
  3. Replies: 2
    Last Post: February 24th, 2014, 10:48 PM
  4. Replies: 41
    Last Post: February 21st, 2013, 05:42 PM
  5. New person Just trying to read a file of ints
    By dubois.ford in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: March 7th, 2010, 11:47 PM