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

Thread: Converting Two dimensional array into an Array list

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Converting Two dimensional array into an Array list

    So I am working on a homework assignment. I say that ahead of time so no one thinks i am being sneaky or what not. However My teacher is asking us to take our two dimensional array we built and rewrite the code so instead of storing the data into the two dimensional array, it will store it into a arraylist and then we will transfer the array list into another class called "Protein". I will post the assignment below so you can get a better understanding of what he is asking. I am a little less then a month new to the language, and the teacher is going way to fast for me to really learn the material. The people in this community have been more then helpful in filling the space my teacher is leaving.
    So here is the assignment
    Assignment 2

    Parsing Biological Data

    Implementing the Protein Class

    Your task is to create a Protein class that holds important protein data and performs basic
    operations on proteins. Below is the same uniprot sample from the rst assignment

    ID HBA_HUMAN Reviewed; 142 AA.
    AC P69905; P01922; Q1HDT5; Q3MIF5; Q53F97; Q96KF1; Q9NYR7; Q9UCM0;
    DT 21-JUL-1986, integrated into UniProtKB/Swiss-Prot.
    DT 23-JAN-2007, sequence version 2.
    DT 28-JUL-2009, entry version 75.
    DE RecName: Full=Hemoglobin subunit alpha;
    DE AltName: Full=Hemoglobin alpha chain;
    DE AltName: Full=Alpha-globin;
    GN Name=HBA1;
    GN and
    GN Name=HBA2;
    OS Homo sapiens (Human).
    OC Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi;
    OC Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini;
    OC Catarrhini; Hominidae; Homo.
    OX NCBI_TaxID=9606;
    ....
    SQ SEQUENCE 142 AA; 15258 MW; 15E13666573BBBAE CRC64;
    MVLSPADKTN VKAAWGKVGA HAGEYGAEAL ERMFLSFPTT KTYFPHFDLS HGSAQVKGHG
    KKVADALTNA VAHVDDMPNA LSALSDLHAH KLRVDPVNFK LLSHCLLVTL AAHLPAEFTP
    AVHASLDKFL ASVSTVLTSK YR
    //

    In addition to the primary accession number and sequence, the Protein class will hold the
    description of the protein as well as the source organism. In the sample above, the descrip-
    tion and source organism are Hemoglobin subunit alpha and Homo sapiens (Human). In
    order to access and modify this information, your class must implement getter and setter
    methods for each private instance variable. In addition to these methods, you must override
    (implement) the following class methods:

    public String toString(): Implementing this method will allow us to directly print
    useful information about proteins using System.out.println(protein). This method
    should return a String formatted as follows:

    AC: <the primary accession number>
    DE: <the description>
    OS: <the source organism>
    SQ: <the sequence>

    public boolean equals(Protein otherProtein): When the equals method is called
    (e.g. myProtein.equals(otherProtein)), it should return true only if myProtein
    and otherProtein are the same protein. Implementing this method correctly will require
    us to use the keyword this which we will discuss in lab.

    Extending the Parser class

    Your next task is to enhance the parser so that it can read in every uniprot le that lives in
    some directory (folder). In particular, you must implement the following:

    public class Parser{
    //global variable that stores all of the proteins.
    private ArrayList<Protein> protein_database = new ArrayList<Protein>();
    .
    .
    .
    /*
    fills the protein_database arraylist with all the proteins
    defined in the uniprot files that exist inside the directoryName folder.
    */
    public static void parseAll(String directoryName){
    //CODE GOES HERE
    }


    You will need Java's ArrayList and File class to correctly implement the recursive method
    parseAll. File methods such as isDirectory, exists, list, and listFiles will be quite
    helpful. In a nutshell, an ArrayList is an expandable array that allows us to add elements
    without knowing the size of the array in advance.
    Since we are no longer concerned with outputting to a le, the main method of your Parser
    class must be as follows:

    public static void main(String[] args){
    //outputs a list of all the proteins defined in the uniprot files
    //that reside in the folderName folder
    String folderName = args[0];
    parseAll(folderName);
    System.out.println(protein_database);
    }

    Speci cations, notes, and hints

    The name of the source code les must be Parser.java and Protein.java . The program
    should be executable as: java Parser uniprotDirectory where uniprotDirectory is
    the name of the directory (folder) that contains the uniprot les.

    Since we are now interested in holding more protein data (other than AC and SQ),
    you will need to adjust your parse method to extract this new data.

    Do not assume that only uniprot les live in uniprotDirectory. You may assume that
    all uniprot les will end in .dat.

    ArrayLists will allow you to make your parse method simpler.

    Sorry it is such a long explanation.
    Also if someone could help me understand WHAT he is wanting me to do in this assignment that would be appreciated. He does not explain very clearly what he is asking.

    Ok so here is my assignment as of now. The only part i have added for assignment two is looking for the "DE" and the "OS" in the while loop in the method "extract_data"

    import java.util.*;
    import java.io.*;
     
    public class Parser 
    {
    	    public static void main(String[] args) throws IOException
    	    {	
    	    	PrintWriter out = new PrintWriter("fastaFile");
    	    	String[][] extractedInfo = extract_info();
    		int n = count_entries();
     
    	    	for(int i = 0; i < n; i++)
    	    	{
    			out.write("<"+extractedInfo[i][1]+"\n"+extractedInfo[i][0]+"\n"
    						 +extractedInfo[i][2]+"\n"+extractedInfo[i][3]+"\n");
    	    	}
     		out.close();	        
    	    }
     
     
    	    public static String[][] extract_info() throws IOException 
    	    {
    		String[][] extractedData = new String[count_entries()][4];
    	    	File uniprot = new File ("uniprotFile");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    	int i = 0;
    	    	boolean foundAC = false; //stored in [i][1]
    	    	boolean SQMode = false; //stored in [i][0]
    	    	String sequence = "";
    	    	boolean foundDE = false; //stored in [i][2]
    	    	boolean foundOS = false; //stored in [i][3]
     
    	    	while (uniprotScanner.hasNextLine())
    	    	{
    	    		String currentLine = uniprotScanner.nextLine();
    	    		String[] tokens = currentLine.split(" ");
     
    	    		if ( tokens [0].equals("AC") && !foundAC )
    	    		{
    	    			extractedData[i][1] = tokens[3];
    	    			foundAC = true;
    	    		}
    	    			else if (tokens [0].equals("SQ") && !SQMode)
    	    			{
    	    				SQMode = true;
    	    			}
    	    			else if (tokens [0].equals("DE") && !foundDE)
    	    			{	
    	    				extractedData[i][2] = currentLine;
    	    				foundDE = true;
    	    			}
    	    			else if (tokens [0].equals("OS") && !foundOS)
    	    			{
    	    				extractedData[i][3] = currentLine;
    	    				foundOS = true;
    	    			}
    	    				else if (currentLine.startsWith("//"))
    	    				{
    	    					SQMode = foundAC = foundDE = foundOS = false;
    	    					extractedData[i][0] = sequence; 
    	    					sequence = "";
    	    					i++;
    	    				}	
    	    					else if (SQMode)
    	    					{
    	    						sequence += currentLine.replaceAll(" ", "");
    	    					}	    		    					
    	    	}	
    	    	return extractedData;
    	    }
     
    	    public static int count_entries() throws IOException
    	    {
    	    	int entriesCount = 0;
    	    	File uniprot = new File ("uniprotFile");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    while (uniprotScanner.hasNextLine())
    	    { 
    	    	String currentLine = uniprotScanner.nextLine();
    	    	String[] tokens = currentLine.split(" ");
     
    	    	if (tokens [0].equals("//"))
    	    	{
    	    		entriesCount++;
    	    	} 
    	    }
    	    return entriesCount;
    	    }
     }

    Now in this code I am saving the data I have found into a two dimensional array. Now he wants us to change that so it is saving into an arraylist and then save that array list into another class called "Protein".

    I would much rather just save the two dimensional array into an arraylist. How can this be achieved.

    I know I am asking alot of this community and have presented alot of information, but I thank anyone who is willing to spend the time to provide me some clarification


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting Two dimensional array into an Array list

    Converting a 2D array to an arraylist (a dynamic 1D array)
    Given a 2D array with 2 rows and 3 columns:
    1 2 3
    4 5 6
    What would the arraylist/1D array look like?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Converting Two dimensional array into an Array list

    The array list would have to be formatted

    public String toString(): Implementing this method will allow us to directly print
    useful information about proteins using System.out.println(protein). This method
    should return a String formatted as follows:

    AC: <the primary accession number>
    DE: <the description>
    OS: <the source organism>
    SQ: <the sequence>

    I changed my code around actually so this is the new code

    import java.util.*;
    import java.io.*;
     
    public class Parser 
    {
    	private static ArrayList<Protein> protein_database = new ArrayList<Protein>();
     
    	    public static void main(String[] args) throws IOException
    	    {	
    	    	PrintWriter out = new PrintWriter("fastaFile");
    	    	String[][] extractedInfo = extract_info();
    		int n = count_entries();
     
    	    	for(int i = 0; i < n; i++)
    	    	{
    			out.write("<"+extractedInfo[i][1]+"\n"+extractedInfo[i][0]+"\n"
    						 +extractedInfo[i][2]+"\n"+extractedInfo[i][3]+"\n");
    	    	}
     		out.close();	        
    	    }
     
    	    public static void parseAll(String directoryName)
    	    {
     
    	    }
     
    	    public static void extracted_info(String s) throws IOException 
    	    {
    		String extractedData = new String();
    	    	File uniprot = new File (s);
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    	boolean foundAC = false; //stored in [i][1]
    	    	boolean SQMode = false; //stored in [i][0]
    	    	String sequence = "";
    	    	String ACline = "";
    	    	String DEline = "";
    	    	String OSline = "";
    	    	boolean foundDE = false; //stored in [i][2]
    	    	boolean foundOS = false; //stored in [i][3]
     
     
    	    	while (uniprotScanner.hasNextLine())
    	    	{
    	    		String currentLine = uniprotScanner.nextLine();
    	    		String[] tokens = currentLine.split(" ");
     
    	    		if ( tokens [0].equals("AC") && !foundAC )
    	    		{
    	    			ACline = tokens[3];
    	    			foundAC = true;
    	    		}
    	    			else if (tokens [0].equals("SQ") && !SQMode)
    	    			{
    	    				SQMode = true;
    	    			}
    	    			else if (tokens [0].equals("DE") && !foundDE)
    	    			{	
    	    				DEline = currentLine;
    	    				foundDE = true;
    	    			}
    	    			else if (tokens [0].equals("OS") && !foundOS)
    	    			{
    	    				OSline = currentLine;
    	    				foundOS = true;
    	    			}
    	    				else if (currentLine.startsWith("//"))
    	    				{
    	    					SQMode = foundAC = foundDE = foundOS = false;
    	    					Protein info = new Protein(ACline, sequence, DEline, OSline);
    	    					protein_database.add(info);
    	    					sequence = "";
     
    	    				}	
    	    					else if (SQMode)
    	    					{
    	    						sequence += currentLine.replaceAll(" ", "");
    	    					}	    		    					
    	    	}	
     
    	    }
     
    	    public static int count_entries() throws IOException
    	    {
    	    	int entriesCount = 0;
    	    	File uniprot = new File ("uniprotFile");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    while (uniprotScanner.hasNextLine())
    	    { 
    	    	String currentLine = uniprotScanner.nextLine();
    	    	String[] tokens = currentLine.split(" ");
     
    	    	if (tokens [0].equals("//"))
    	    	{
    	    		entriesCount++;
    	    	} 
    	    }
    	    return entriesCount;
    	    }
     }

    and this is the "Protein" Class as well


    public class Protein {
    	private String proteinAC;
    	private String proteinSQ;
    	private String proteinDE;
    	private String proteinOS;
     
     
    	public Protein(String proteinAC, String proteinSQ, String proteinDE,
    			String proteinOS) {
    		super();
    		this.proteinAC = proteinAC;
    		this.proteinSQ = proteinSQ;
    		this.proteinDE = proteinDE;
    		this.proteinOS = proteinOS;
    	}
    	public String getProteinAC() {
    		return proteinAC;
    	}
    	public void setProteinAC(String proteinAC) {
    		this.proteinAC = proteinAC;
    	}
    	public String getProteinSQ() {
    		return proteinSQ;
    	}
    	public void setProteinSQ(String proteinSQ) {
    		this.proteinSQ = proteinSQ;
    	}
    	public String getProteinDE() {
    		return proteinDE;
    	}
    	public void setProteinDE(String proteinDE) {
    		this.proteinDE = proteinDE;
    	}
    	public String getProteinOS() {
    		return proteinOS;
    	}
    	public void setProteinOS(String proteinOS) {
    		this.proteinOS = proteinOS;
    	}
     
    	public boolean equals(Protein otherProtein)
    	{
    		if (otherProtein.proteinSQ.equals(this.proteinSQ))
    		{
    			return true;
    		}
    		else return false;
    	}
     
    }

    So in my method that extracts the data i now have it just reading into strings and then reading those into the Protein class. So i figured that out. My issue is how to format the Class to output the string like the format above.
    And also I have to write a recursive method to find every ".dat" file in a folder (which contains sub folders and other files that are not ".dat")
    How to do the recursive method I am still very confused on he told me to use

    public static void parseAll(String directoryName)
    	    {
     
    	    }

    This which is the method he wants to find the ".dat" files but i do not know how to check a set of folders to do that. So help on this portion would also be appreciated.
    Thanks again for responding. I know this is alot of information but I am very new to Java and this teacher is teaching us by "throwing us in the water and hoping we learn how to swim" method and i can not learn like that very easily.

    Thanks again

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting Two dimensional array into an Array list

    I know this is a lot of information
    You are right. There is more here than I am interested in working through to understand what you are trying to do. If you can ask specific programming questions, I could help you write java code for it.

    write a recursive method to find every ".dat" file in a folder (which contains sub folders and other files that are not ".dat")
    Write a method that takes a File object for a directory as argument, lists its contents and checks if any are directories. If they are directories, then calls itself with the File object for that directory.
    Last edited by Norm; September 28th, 2012 at 05:57 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Sep 2012
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Converting Two dimensional array into an Array list

    I appreciate the quick reply. So what i am curious is with are two things at the moment

    first: Is how to write this recursive method to check all files, because all i know is that these methods call themselves until the base case is reach, however i do not know the "Skeleton" on how to do this
    Second: How do i format each string inside the:

    Protein info = new Protein(ACline, sequence, DEline, OSline);
    	   protein_database.add(info);

    so when we do the println on the proteins they print in the format stated above

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting Two dimensional array into an Array list

    This is the basic structure: the method takes a File object for a directory as argument, lists its contents and checks if any are directories. If they are directories, then calls itself with the File object for that directory.

    How do i format each string
    The toString() method would return whatever information about the class that you want displayed. If you want the String to display on multiple lines, include the newline character: \n in the String where you want the line to end and a new one to start.
    Last edited by Norm; September 28th, 2012 at 06:20 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Sep 2012
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Converting Two dimensional array into an Array list

    Ok so the recursive method also needs to check each directory for files ending in ".dat" so how would i be able to:
    first: call the file name in to be "recursed"
    second: make each name in first folder be Strings so i can then run the
    string.endsWith(".dat"); command on it?
    last: continue into each individual folder inside because the first folder will have multiple folder that need to be checked individually. i feel that this method would just check one set of folders and then end

    So for instance i could do

    protein.toString("AC: " + ACline +"\n" +"SQ: " + SQline +"\n" + "DE: " + DEline + "\n" + "OS: " + OSline + "\n");

    also how would i get it to display in this method if my teacher were to call a println command? Would the above code store it in that way? or would it have to be printed that way?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting Two dimensional array into an Array list

    For the recursive method's first version, just print out the files that are found in the folder.
    Later worry about selecting some of them based on their extension.

    protein.toString("AC:....
    You need to look at how to define a method. That is not how a method is defined.
    It looks like a call to a method that is passing it a String as an arg.
    The toString() method returns a String.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Sep 2012
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Converting Two dimensional array into an Array list

    Ok so what is a good command that can even open a file or find a folder on a desktop? I don't know how to do that at all. And i read an article that discusses the "Tree" set of data which this would be if im correct. So would the method have to check down one entire set of folders and then check through the other branch? Or would it go folder layer by folder layer (if that makes sense).
    Finally are you saying that I need to create a method that prints out the protein?
    my assignment shows this way
    public String toString():
    but in the parameters of that would i do what i did above by printing it out? Or would i do that inside the method itself?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting Two dimensional array into an Array list

    command that can even open a file
    Not sure what you are asking. There are classes and classes have methods. There are NO commands.
    Not sure what "open" means. For text files, the Scanner class has some easy to use methods that can be used to read the contents of a file. It the file's contents are not lines of text there are other classes that would be better.
    find a folder on a desktop
    The JFileChooser class will open a dialog to allow a user to find a file.


    If you are working on listing the files in a folder, start with a simple program first that is given a folder and lists the files in that folder. Nothing more.
    When that works, add code to only display the names of certain files.
    When that works, add code to display the contents of sub folders.

    Start with the simplest, get that to work before moving to the next.

    a method that prints out
    The toString() method does NOT print out anything. It returns a String that contains the data describing the object it is in.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Sep 2012
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Converting Two dimensional array into an Array list

    SO what i have to do in this program. Is read in a folder (of the users choose run through command line) then once that is open find all the ".dat" files inside each folder inside (each folder CAN contain more folders and coan contain files that are not .dat) Once i find each file I am to find the required information out of each filer (I have done that) and save each into the Protein Class (which i have also done) From there I need to follow this (taken directly from my assignment)

    public String toString(): Implementing this method will allow us to directly print
    useful information about proteins using System.out.println(protein). This method
    should return a String formatted as follows:
    AC: <the primary accession number>
    DE: <the description>
    OS: <the source organism>
    SQ: <the sequence>
    So this is where I am confused. How do i do the above so when they print it out it is formatted as such.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting Two dimensional array into an Array list

    Lets work on one problem at a time.
    I suggest that you start with a simple program that is given the name of a folder and that prints out the names of all the files in that folder. Nothing more.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Help with looking through a two-dimensional array.
    By aesguitar in forum Algorithms & Recursion
    Replies: 14
    Last Post: June 1st, 2012, 11:10 AM
  2. Help with one-dimensional array
    By brandon66 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: April 26th, 2012, 04:59 PM
  3. Array List of Array Lists working for first item but not for second.
    By javapenguin in forum Collections and Generics
    Replies: 6
    Last Post: February 15th, 2012, 05:12 PM
  4. Input in a two Dimensional Array.
    By Mr.777 in forum File I/O & Other I/O Streams
    Replies: 29
    Last Post: December 14th, 2011, 11:40 PM
  5. Single Dimensional Array Help!
    By Allicat in forum What's Wrong With My Code?
    Replies: 6
    Last Post: March 15th, 2011, 12:01 PM

Tags for this Thread