473,320 Members | 1,724 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Deliminating While Reading a File

I have a file that I want to read from and take the first line with two integers and store them into separate variables, and then store the last line of two characters as integers. Like so:

5 5
5 5 5 5 5 5
0 0 0 0 0 5
5 5 0 5 0 5
5 5 0 5 5 5
5 0 0 0 0 0
5 5 5 5 5 5
1 0

I can read the file fine and put it into a multidimensional array, like so:

Expand|Select|Wrap|Line Numbers
  1. public static void main(String[] args) throws IOException{
  2.         int[][] array = new int[6][6];
  3.  
  4.         Scanner fileScan;
  5.         fileScan = new Scanner(new File ("nums.txt"));
  6.         fileScan.useDelimiter("\n");
  7.  
  8.         int i = 0;
  9.         while (fileScan.hasNext()){
  10.             String str = fileScan.next();
  11.             Scanner stringToIntScanner = new Scanner(str);
  12.             int j = 0;
  13.             while (stringToIntScanner.hasNext()){
  14.                 array[i][j] = stringToIntScanner.nextInt();
  15.                 j++;
  16.             }
  17.             i++;
  18.         }
  19.         PrintArray(array);
  20.     }
  21.  
  22.     public static void PrintArray(int[][] array){
  23.         for (int i = 0; i < array.length; i++){
  24.             for (int j = 0; j < array[i].length; j++){
  25.                 if (j < array.length - 1)
  26.                     System.out.print(array[i][j] + " ");
  27.                 else
  28.                     System.out.print(array[i][j]);
  29.             }
  30.             System.out.println();
  31.         }
  32.     }
  33.  
I just can't figure out what method to use in the String class to only take the first line and convert the "5 5" into two integer variables. I am unsure syntactically how to use the String.split() method correctly and convert them to integers.
Apr 23 '09 #1
8 2294
dmjpro
2,476 2GB
First of all don't use "\n", use instead System.getProperty("line.separator").

String.split(), see Java Doc. What you read there?
Apr 23 '09 #2
JosAH
11,448 Expert 8TB
If the file only contains numbers why don't you just use fileScan.nextInt() each time you want to read one? There is no need to read Strings and fiddle with those.

kind regards,

Jos
Apr 23 '09 #3
@dmjpro
"\n" and line separator are virtually the same thing right? does it matter then?

I can now setup my array but I can't get any of the integers in the file to fill in the array. Am I using nextInt() wrong?

Expand|Select|Wrap|Line Numbers
  1. Scanner fileScan;
  2.         fileScan = new Scanner(new File ("inputfile.txt"));
  3.         fileScan.useDelimiter("\n");
  4.  
  5.         String str = fileScan.next();
  6.         Scanner stringToIntScanner = new Scanner(str); 
  7.         int size1 = stringToIntScanner.nextInt();
  8.         int size2 = stringToIntScanner.nextInt();
  9.  
  10.         int[][] maze = new int[size1][size2];
  11.  
  12.         PrintArray(maze);
  13.         System.out.println();
  14.  
  15.         int i = 0;
  16.         int j = 0;
  17.          while (stringToIntScanner.hasNext()) {
  18.              maze[i][j] = stringToIntScanner.nextInt();
  19.              j++;
  20.          }
  21.          i++;
  22.          PrintArray(maze);
That first printArray method prints the empty array... I just cant get the array to fill, I think its my call to hasNext() in my while loop that is screwing things up. Any suggestions?

Thank you all for your input, it is most appreciated.
Apr 23 '09 #4
JosAH
11,448 Expert 8TB
Why are you ignoring my reply #3?

kind regards,

Jos
Apr 23 '09 #5
@JosAH
I'm sorry, I'm new to this forum.

I am using nextInt(); but for some reason after I use the two nextInt() statements and store the variables into the multidimentional array, it doesn't fill the array at all.

Line 12 should print all 0's throughout the multidimentional array, but after that its not being filled correctly.
Apr 23 '09 #6
JosAH
11,448 Expert 8TB
@MidnightPhyre
No need to say sorry; have a look at the following example code; please notice that only one Scanner object is used and it is used to read all the int numbers from the input.

Expand|Select|Wrap|Line Numbers
  1.     public static void main(String[] args) {
  2.  
  3.         Scanner in= new Scanner(System.in);
  4.         int rows= in.nextInt();
  5.         int cols= in.nextInt();
  6.  
  7.         int[][] a= new int[rows][cols];
  8.  
  9.         for (int r= 0; r < rows; r++)
  10.             for (int c= 0; c < cols; c++)
  11.                 a[r][c]= in.nextInt();
  12.  
  13.         for (int r= 0; r < rows; r++) {
  14.             for (int c= 0; c < cols; c++)
  15.                 System.out.print(a[r][c]+" ");
  16.             System.out.println();
  17.         }
  18.     }
  19.  
kind regards,

Jos
Apr 23 '09 #7
@JosAH
That portion of code for filling the array does not work for me. I get a "No Such Element Exception" when I use it.

I changed my code around a bit, but it still wont fill the array from the scanner correctly, although it will establish the size of the multidimensional array.

Expand|Select|Wrap|Line Numbers
  1. Scanner fileScan;
  2.         fileScan = new Scanner(new File ("inputfile.txt"));
  3.         fileScan.useDelimiter("\n");
  4.  
  5.         Scanner scan = new Scanner(fileScan.next()); 
  6.         int row = scan.nextInt();
  7.         int column = scan.nextInt();
  8.  
  9.         int[][] maze = new int[row][column];
  10.  
  11.          while (scan.hasNext()){
  12.              for(int r = 0; r < maze.length; r++){
  13.                 for (int c = 0; c < maze[r].length; c++){
  14.                     maze[r][c] = scan.nextInt();
  15.                     c++;
  16.                 }
  17.                 r++;
  18.             }
  19.         }
  20.  
  21.          PrintArray(maze);
  22.  
Apr 23 '09 #8
JosAH
11,448 Expert 8TB
@MidnightPhyre
Then the structure of your file is incorrect, e.g. your file says it contains r rows and c columns but it doesn't contain r*c integers.

The code snippet I posted works fine if the file is fine.

kind regards,

Jos
Apr 24 '09 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
19
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much...
4
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile =...
6
by: Rajorshi Biswas | last post by:
Hi folks, Suppose I have a large (1 GB) text file which I want to read in reverse. The number of characters I want to read at a time is insignificant. I'm confused as to how best to do it. Upon...
1
by: Need Helps | last post by:
Hello. I'm writing an application that writes to a file a month, day, year, number of comments, then some strings for the comments. So the format for each record would look like:...
7
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should...
5
blazedaces
by: blazedaces | last post by:
Ok, so you know my problem, java is running out of memory reading with SAX, the event-based xml parser intended more-so than DOM for extremely large files. I'll try to explain what I've been doing...
6
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features...
2
by: Derik | last post by:
I've got a XML file I read using a file_get_contents and turn into a simpleXML node every time index.php loads. I suspect this is causing a noticeable lag in my page-execution time. (Or the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.