Results 1 to 10 of 10
  1. #1
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default swapping the contents of the file and writing to another file

    hi
    i have a problem
    i have to read contents from the file and my input file1.txt is like this

    G101 G102 G104 G105 G109
    G178 788 832 736 534
    G103 645 623 937 435
    G925 724 693 024 087
    G510 123 627 802 510

    and my output file should be like this
    G101 G178 G103 G925 G510
    G102 788 645 724 123
    G104 832 623 693 627
    G105 736 937 024 802
    G109 534 435 087 510

    the logic behind the problem is to keep the diagonal elements as such as and replace the other elements by storing it in a temporary variables and swapping them (ie)(0,1) should be swapped to (1,0) and so on..

    so i started with reading a each line from the input file..but i need to read each and every element and store it in a two dimensional array..

    import java.io.*;

    class swap
    {
    public static void main(String args[])throws IOException
    {
    try
    {
    FileInputStream in=new FileInputStream("File1.txt");
    BufferedReader br=new BufferedReader(new InputStreamReader(in));
    String myarray[]=new String[25];
    for (int i=0;i<myarray.length;i++)
    {
    myarray[i]=br.readLine();
    }
    System.out.println(myarray[4]);
    }
    catch(IOException e)
    {
    System.out.println(e);
    }

    }

    }

    can someone plz help me in solve this problem...

  2. #2
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Question Partial result

    I worked on it awhile, I got to:
    Java Code:
    //  SWAP.java:77: warning: [unchecked] unchecked conversion
    // found   : java.util.Stack
    // required: java.util.Stack<java.lang.String>
    //                Stack<String> s = (Stack) list.removeFirst();//
    //                                  ^
    Maybe someone who knows Generics and Intro to Graph Theory can lend us some pointers and snippets. I need this to work as well. As a header, I have found Algorithms in Java by Sedgewick to be the best of best on gaining ground on this area. With that said, here is:
    Java Code:
    // Logic is keep the diagonal elements as such,
    // replace the other elements by storing it in a temporary variables
    // and swapping them (ie)(0,1) should be swapped to (1,0) and so on..
    
    // Read each line from the input file,
    // swap every element.
    
    import java.io.*;
    import java.util.*;
    
    // Preliminary work, to be a starting place.
    
    public class SWAP
    {
      File outputFile;
      public SWAP(String fileName)
      {
          // Construct this with filename
          // to be used for data retention.
          outputFile = new File ( fileName );//
      }
      // Temporary utilities while
      // considering the problem.
      LinkedList<Stack> list = new LinkedList<Stack>();
    
      // Your instructor will direct for loop syntax, not do{}while();
      public void swap(File elements)throws IOException
      {
        // Crude beginnings of Directed Acyclic Graph
        try
        {
            // File taken as method call parameter
            FileInputStream in=new FileInputStream(elements);
            BufferedReader br=new BufferedReader(new InputStreamReader(in));
            LineNumberReader lnr = new LineNumberReader(br);
            // Result.
            FileOutputStream out=new FileOutputStream(outputFile);
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(out));
            // Check for non-null first line.
            String nextLine= lnr.readLine();
            if( nextLine != null )
            {
                int sizeStackedUp = 0;//
                do
                {
                    Stack<String> stack = new Stack<String>();
                    Vector<String> lineBuffer =
                       new Vector<String>(
                            Arrays.asList(
                               nextLine.split(" ")));
                    sizeStackedUp = lineBuffer.size();
                    // Push each element onto stack ?...
                    for(String s : lineBuffer)stack.push(s);
                    // Build list of Stacks
                    list.addLast(stack);
                }
                while(nextLine !=null );
                // At this point, we have a List of Stacks
                do
                {
                    // Print each stack
                    Stack<String> s = (Stack) list.removeFirst();//
                    for(String next : s)bw.write(next,0,next.length());
                }
                while(list.size() > 0x00000000);
            }
            else
            {
                // Nothing to do.
                return;
            }
            // Printing
         }
         catch(IOException e)
         {
           System.out.println(e);
         }
      }
    }
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    The logic for this could be:
    Read all the lines from the file and save them as Strings in an array
    large enough to hold them. After reading all the lines from the file, you know how large the array needs to be (its given that the number of colums = the number of rows.
    Create a two dimensional array that size.
    String[][] anArray = new String[theSize][]; // create an 2dim array
    Loop thru the saved lines from the file and split them into parts using something like StringTokenizer or ???
    Create the second dimension of the array to hold the elements of a line:
    anArray[i] = new String[theSize]; // create second dimension for this line i
    Store each token in a line as an element in the array.
    anArray[i][j] = theToken; // save the element at its location j for this line

    Now write a loop to swap the elements along the axis.

  4. #4
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default

    i could read the contents in single dimension array..here is the code for it....but i want it to be stored in two dimension array..how do i do that..the person above has explained it but since i am new to java.. i am struggling and i am confused..

    b = new BufferedReader(new FileReader("File1.txt"));
    while ((Str = b.readLine()) != null)
    line.add(Str);

    String [] arr = new String[line.size()];

    for (int i = 0; i < map.length; i++)
    {
    Str = (String) line.get(i);
    StringTokenizer st = new StringTokenizer(Str);
    while (st.hasMoreTokens()){
    arr[i]=st.nextToken();
    System.out.println(arr[i]);
    }

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    A discussion on multidimensional arrays in Java. They're weird! They are not symmetrical, more like trees. Each sub dimension can be a different length and can handled separate from the others.
    When an array of objects is defined, all of the members of the array are null.
    For an example I'll define a 2 dim array and then populate it:
    Java Code:
      String anArray[][] = new String[5][]; // first dimension has 5 
      anArray[0] = new String[2]; // first of 5 on second dimension has 2
      anArray[1] = new String[4]; // second of 5  has 4
      anArray[0][0] = "0,0";  // put value into position 0,0
      anArray[0][2] = "Past end of array"; // error only 2 elem: 0 and 1
      anArray[1][3] = "1, 3";  // put value in end of 2 of 5 leaving others null
      anArray[1][1] == null;   // true, nothing assigned yet
    In your program, after you read in the file, you can create the two dim array as above for the number of lines.
    Then in a loop with i as index, get the next line from the vector, tokenize it, get the number of tokens and add a sec dim on the array:
    anArray[i] = new String[nbrOfTokens];
    Now using j as an index get the tokens and assign them to the elements of that array: anArray[i][j] = next token;
    incr j thru the tokens from 0 to #of tokens-1
    incr i thru the lines from 0 to #oflines-1
    When you get out of the loops, the array should be full of the tokens from the file.

  6. #6
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default trees

    Norm: They are not symmetrical, more like trees.
    That is very much correct, trying to construct n-dimensioned data objects in Java is ineffective. Trees ( and related data structures ) may be used effectively but is beyone the skill level here.
    Java Code:
    // Two dimensional array.
    Object[][] ob = new Object[4][5];// Any number 
    int OuterIndex = ob.length;
    int InnerIndex = ob[].length;//
    for( OuterIndex++ )
    {
        for( InnerIndex++ )
        {
             ob[OuterIndex][InnerIndex];
    Many detalis omitted, Norm can fill it in or I will help him. Swamped right now.

    Norm, read Algorithms in Java: Graph Algorithms - Google Book Search
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  7. #7
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default

    Thankyou very much...
    i could store the elements in the two dimensional array..but i have problem in displaying it in two dimensional format in the console..

    now i could store in elements i want to swap the elements

    i have tried a sample code here is it
    Java Code:
    class twodim
    {
      public static void main(String args[])
       {
         String a2[][]=new String[3][3];
          a2[0][0]="G101";
          a2[0][1]="G267";
          a2[0][2]="375";
          a2[1][0]="983";
          a2[1][1]="883";
          a2[1][2]="601";
          a2[2][0]="683";
          a2[2][1]="583";
          a2[2][2]="483";
        System.out.println(a2.length);
        
        for (int r=0; r < 3; r++) {
        for (int c=1; c < 3; c++) {
    
            String temp=a2[r][c];
            a2[r][c]=a2[c][r];
            a2[c][r]=temp;        
        }    
       }
       for(int i=0;i<a2.length;i++)
        {
          for(int j=0;j<a2[i].length;j++)
           {
            System.out.println(" "+a2[i][j]);
           }
          
           System.out.println("");
         }
    }
    }
    but the problem is [1,2] and [2,1] is not getting swapped?
    i am not able to figure out the problem..

    o/p i got:
    Java Code:
    G101
    983
    683
    
    G267
    883
    601
    
    375
    583
    483

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    In your swapping loop the column index should start at the row index + 1 vs at 1.

    To print items on the same line use the print() method with a trailing space for separator and then use a println() to flush the line/go to the next line

  9. #9
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default row major / colum major

    Last edited by Nicholas Jordan; 07-10-2008 at 04:41 PM. Reason: simplifiy
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  10. #10
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

Similar Threads

  1. Viewing contents of zip file
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-03-2008, 05:16 PM
  2. Concatenation file contents
    By Java Tip in forum Java Tip
    Replies: 1
    Last Post: 02-07-2008, 01:29 PM
  3. Adding file contents to Choice component
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-07-2008, 09:06 AM
  4. Reading file contents (BufferedReader)
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-07-2008, 09:00 AM
  5. Viewing contents of JAR file
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-21-2007, 03:12 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •