Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Read file char by char and save chars into a 2D array

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I want to read a file char by char and save the input into a 2D Array. This is what I wrote but its wrong. However, I cant save the character elements in the array properly and when I execute the program, when I print the array in which I saved the characters read from the txt file, the output is extremely wrong and incoherent. So in my program, the input is given via the command line, through a txt file. The txt file contains some char elements. Every row of the file's input, has no matter the file, the same elements. The chars from the input file have to be saved in a 2d array (I ignore the new line character when I save the elements from the txt file into my 2d array). The size of this array is known to me. Since concerning the input file, every line has the same number of elements so I can derive the number of rows. This is the code I wrote but it gives wrong output. The input Give through the file:

+.........-
-+--------.

The wrong output :

++++++++++++++++++++........................................Number of lines: 2
Number of chars: 20
Number of columns: 10
import java.util.*;
import java.io.*;

public class Doomday2 {
public static void main (String args[]) throws FileNotFoundException {
   Scanner scanner = new Scanner(new File(args[0]));
   scanner.useDelimiter("");
   int numberOfLines = 0, count_chars=0, rows=0, i=0, j=0;
   while(scanner.hasNext()) {
       char c = scanner.next().charAt(0);

       if(c == System.getProperty("line.separator").charAt(0)) {
           numberOfLines++;
           continue;
       }
       else count_chars++;     // do something with char
    }

   rows = count_chars /numberOfLines;
   //scanner.close();
   Scanner scanner2 = new Scanner(new File(args[0]));
   char[][] a = new char[1000][1000];
   while(scanner2.hasNext()){
       char c = scanner2.next().charAt(0);
       if(c == System.getProperty("line.separator").charAt(0)) {
           continue;
       }
       else {
           for( i=0;i<numberOfLines;i++){
               for (j=0; j< rows; j++){
                // System.out.print(a[i][j]);
                a[i][j]=c;
                System.out.print(a[i][j]);
               }
           }
       }
   }
   //for(int i=0;i<counter;i++)
  // {
    //   System.out.print(a[i]);
  // }

  for( i=0;i<numberOfLines;i++){
     for (j=0; j< rows; j++){
         System.out.print(a[i][j]);

     }
  }
   System.out.println("Number of lines: " + numberOfLines);
   System.out.println("Number of chars: " + count_chars);
   System.out.println("Number of columns: " + rows);
   scanner.close();
   scanner2.close();
}

}
 
Marshal
Posts: 74359
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

Mary Tsamp wrote:I want to read a file char by char . . .

No, you don't. Sorry to sound so negative, but that is correct.
Avoid low‑level constructs like chars when you can use line by line. What is more, Scanners are intended for reading Strings, not individual chars. Your post makes it sound as though you had decided what technique to employ before you decided what you want to achieve. Let's have a look at the code; I shall start with the code tags; you didn't quite get them right. [code=java] goes before the code and [/code] after it, then your code will look like this:-That looks like far too much code to put in the main method; haven't you been taught any object‑oriented programming?

So, that code looks for line end characters to count the lines. If you go through the Scanner documentation, you will find methods which can tell yuo whether there are any more lines, and a method to read something, even a whole line and move you to the next whatever. You can use those methods together with lineCount++; to count lines. By the way, the Java® way to write such a variable is charCount not count_chars. The underscore _ should only be used in constants and package names. There are other style things, but let's orget them jsut for the moment.
Close the first Scanner before you open the second. In fact, you should use the construct described in this Java™ Tutorials section to open your Scanners; that obviates the need to write close() at all.
You have missed out something you used in your first Scanner when you opened the second Scanner. That will produce a result different from what you expect, but I think the real problem is that you are trying to go from a high‑level construct (a nextXXX() method of Scanner's which returns a String) to a low‑level construct (a char[]). If you have something high‑level, stick with that high‑level something. You can do things with it. Who needs to count chars when a String object has a method which does it for you? You know how many lines there are, so why guess at a 1000‑element array? You should forget about 2D arrays; that isn't one. It is an array of arrays. If you really wanted a char[][], which I think you don't, you can create a char[] from a String very easily.

I am sorry, but I think you would do better to start from scratch. I would use one Scanner and put the lines into a List of Strings, but you might not yet know how to use a List. In that case, have one method to count the lines, and a second method to read the lines into a String[]. Once you have that array, there are all sorts of things you can do with it; the high‑level entity String gives you much more power and flexibility than you would ever get from a char[].
 
Mary Tsamp
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What do you mean start from  scratch?? Just because you cant help me that does not mean you have to offend me! or maybe o got you wrong
I only know C language! No! i am not familiar with object orienting programming, I am trying to learn java, and yes you don't help.

Anybody else to help me achieve what I am asking quidance for?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic