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

Thread: Need help with understanding a homework assignment, not asking for answers

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

    Default Need help with understanding a homework assignment, not asking for answers

    So i am brand new to Java and i am currently taking a class about it, but my problem is the teacher is awful, and i can not learn anything from him. He has given us a "simple" assignment around objects and string files, however i have literally no idea how to write any of the code, nor do i understand what he is asking of me on the assignment. So i would like to post the assignment on here and have you guys give me an idea of what he is looking for and suggestions on how to do that. Again i am NOT looking for you to give me the answers, i just want some help.

    Parsing Uniprot Files
    Uniprot is a comprehensive data source about proteins. It contains protein sequences and
    information about proteins in a large number of species. As computer scientists, you can
    think of a protein sequence as a string over the alphabet of amino acids. For example, the
    sequence of one component of the human hemoglobin protein (its alpha subunit) is:

    MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLS HGSAQVKGHG
    KKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTL AAHLPAEFTPA
    VHASLDKFLASVSTVLTSKYR

    The id given by Uniprot to this protein is P69905. This id is called an accession number
    (AC). The Uniprot knowledgebase is available in a variety of formats, including a simple
    at
    le format that you are going to parse. Part of the entry for the hemoglobin alpha globin is
    as follows:

    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
    //


    Assignment 1
    Things you should know about this format:

     Each type of information is speci ed by a two-letter code at the beginning of the line.
     The accession number for this protein is found in the AC line (and it does not include
    the semi-colon). Note that the protein has several accession numbers, and the rst one
    is the primary accession number.

     The sequence is found in the lines following the SQ line until the end-of-entry ter-
    minator (//). Spaces are not part of the sequence, and are there only for human
    readability.

     Each entry is terminated by //.

    You can nd the Uniprot entry for this protein at Hemoglobin subunit alpha - Homo sapiens (Human).
    The Uniprot knowledge base is also available in XML which is a modern, generic language for
    representing data. Your task is to parse a Uniprot
    at le containing entries for an unknown
    number of proteins (currently the database contains information on 495880 proteins coming
    from 5208 species). For each protein you will need to extract its primary accession number
    and sequence. The data that you extracted then needs to be written to another le which
    contains the accession numbers and sequences, and should have the following format:

    >header1
    sequence1
    >header2
    sequence2
    ....
    >headerN
    sequenceN

    This format is called Fasta (after the name of a program written in the early 90s which used
    this format). Here's a description of the format: FASTA - Wikipedia, the free encyclopedia format.
    In our case the header of the Fasta le needs to contain the primary accession number of
    the protein.

    Speci cations, notes, and hints

     The name of the source code le must be Parser.java. The program should be exe-
    cutable as: java Parser uniprotFile fastaFile where uniprotFile is the le name
    for the input le containing Uniprot entries, and fastaFile is the output le in Fasta
    format.


    Assignment 1

     Your program needs to have at least two methods in addition to the Main method:
    a method for extracting the accession numbers and sequences out of the Uniprot le.
    This method needs to return the data as two arrays (think how to do that, since a
    method can only have a single return value). Also, you don't know in advance how
    many proteins are represented in the Uniprot le, so in order to de ne a arrays of the
    right size you need to count the number of entries in the le. This is the second method
    your program needs to have. Java has data structures that can grow dynamically, but
    you shouldn't use them. As a general rule, only use Java features that were covered in
    class.
    
    I have not started this assignment because i have no clue where to even begin. I have tried talking to the teacher and he tries to teach me in sudo code which doesn't work for me. Any help is appreciated. I am using "Eclipse" 4.2 to do the assignment.

    Thank you.
    again i just need basic knowledge stuff not looking for answers


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help with understanding a homework assignment, not asking for answers

    What is the first step taught in your class?
    Where are you stuck?

    If the assignment is reading and writing files, surely you can get some of the code written. Plan out what you need to do, and see how far you can get.
    You need a program that is executable with command line options. Do you know how to read command line arguments in your program?
    Your program must have a main method? Do you know how to include a main method with the correct footprint?
    Your program must have two additional methods, one of which must return two arrays. Do you know how to return two things from a method which can only return a single value?
    Your program is restricted to only the Java features covered in your class. You are the only one here who was there, so all answers you get here must be evaluated under this criteria.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Thank you for replying to my message.
    What is the first step taught in your class?
    He has told us what a class is, what a constructor does, he told us ABOUT getters and setters, but i am very hazey on what exactly they do, and how to use them.
    Where are you stuck?
    I am stuck on the simple layout of the program itself, and how to start at all, as well as what the commands i should use to call files into the program as well as how to call arrays.
    Your program must have two additional methods, one of which must return two arrays. Do you know how to return two things from a method which can only return a single value?
    and i have literally NO clue how to call two arrays in same function.
    I have taken C++ classes and know that language decently, so if you could tell me what each thing is and how it relates to C++ maybe i would have an easier time understanding the formatting.
    You need a program that is executable with command line options. Do you know how to read command line arguments in your program?
    I do not know how to call command lines at all
    Your program must have a main method? Do you know how to include a main method with the correct footprint?
    and i know HOW to create a main and how to add stuff to it, but the term "footprint" goes over my head, i do not know what that is

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Also he wants us to use the Tokenizer feature as well. again do not know how to implement that

  5. #5
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Quote Originally Posted by NewbieJavaProgrammer View Post
    Thank you for replying to my message.
    You are welcome




    Quote Originally Posted by NewbieJavaProgrammer View Post
    He has told us what a class is, what a constructor does, he told us ABOUT getters and setters, but i am very hazey on what exactly they do, and how to use them.
    Look at your class as an entity which can have material things and abilities. Say for example a person. A person can have their own things, right? A person can perform actions, right? So here is this class Person. He told you about constructors, and you posted no question, so I will assume you know how to use them. Say this person class has an integer variable called age. This person can have their own age. So each object of type Person will have their own private age. So a class for the example may look like this:
    public class Person {
     
       //a constructor for this class where the person's age IS NOT known
       public person() {
          myAge = -1;
       }
     
       //a constructor for this class where the person's age IS known
       public person(int age) {
          this.myAge = age;//this line can set myAge directly because a class has access to it's own private variables
          this.setAge(age);//this line does the same thing as the above line, but is possible to be used outside the Person class.
          //the this keyword is not required in either place above but can sometimes help make things clear to the reader.
       }
     
       //a 'getter' for age
       public int getAge() {
          return myAge;
       }
     
       //a 'setter' for age
       public void setAge(int age) {
          myAge = age;
       }
     
       //private instance variables
       private int myAge;
    }
    By looking at this sample class you can see how a getter and setter are simply methods to get and set the value of a variable. When writing code outside the Person class, you can not set the value of myAge without using the setter method because the variable is private. Nor can you get the value without using the getter. Note that the getter and setter are declared public, thus allowing the use of the method itself, which in turn gives you access to the variable. (Unless you extend the person class but that is a different topic.)




    Quote Originally Posted by NewbieJavaProgrammer View Post
    I am stuck on the simple layout of the program itself, and how to start at all, as well as what the commands i should use to call files into the program as well as how to call arrays.
    This is where pseudo code comes in play. Think out the problem in English. How would you solve it? Write it down the way it comes to your mind:
    "Well, first thing I need to do is to get the file names from the user..."
    "Then I need to read the files and extract ......"
    "....etc"

    Then apply your assignment restrictions as you refine your English. You have to get the file names from the user, but you have specific instructions on how to do that. You are told they are to be command line options. That means when you launch your java program from a terminal, you must supply the name of the file to be opened, and the name of the file for your output to be written to. Do a search for "java command line options" or something similar.




    Quote Originally Posted by NewbieJavaProgrammer View Post
    and i have literally NO clue how to call two arrays in same function.
    I have taken C++ classes and know that language decently, so if you could tell me what each thing is and how it relates to C++ maybe i would have an easier time understanding the formatting.
    You can return more than one value from a function if that 'value' is a group of things, or a group of groups of things, or a group of groups of groups etc.... you get the idea. A search on the topic may include words like java, return, multiple and method.




    Quote Originally Posted by NewbieJavaProgrammer View Post
    I do not know how to call command lines at all
    Try searching for "launch java program from command line".




    Quote Originally Posted by NewbieJavaProgrammer View Post
    and i know HOW to create a main and how to add stuff to it, but the term "footprint" goes over my head, i do not know what that is
    Above I wrote out a sample class with two constructors and two methods. Here are the footprints for each in the same order they are found in the sample class:
    public Person();
    public Person(int);
    public int getAge();
    public void setAge(int);
    What does this mean? So many ways to word it, again I refer you to your favorite search engine. All methods have a footprint which is how they are identified. Notice how the constructors are different, but both named Person. Their footprint is the same as far as the method name goes, but the footprint also includes the return types and parameters. So the constructors have two different footprints because the second one has a parameter of type int that is used to set the person's age. As a hint to you, the footprint of the main method has something to do with command line options.
    Take it one step at a time and ask questions when you get stuck. Someone will surely reply.

  6. The Following User Says Thank You to jps For This Useful Post:

    Eriosblood (September 23rd, 2012)

  7. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Start with figuring out what it is the program is suppose to do. Start big and work your way down.

    To help you get started:

    1. You need at least a class called Parser. This class should have at least 3 methods: a main method, and two other methods.

    2. The main method takes in two command line arguments to two file names. You need to open these and parse through them.

    3. One method counts the number of entries in the le

    4. One method extracts the accession numbers and sequences

    Already you have enough information to start framing your program.

    public class Parser
    {
        /**
        * This is the main method. It takes two command-line args, the uniProtFile and fastaFile. It uses these to parse out some information.
        */
        public static void main(String[] args)
        {
            // the two file names are inside the array args
            // args[0] has the uniProtFile filename
            // args[1] has the fastaFile filename
        }
     
        /**
        * This method is suppose to extract the accession numbers and sequences
        */
        public static void extract_info() // note: this method does NOT have the correct return type or method parameters!
        {
        }
     
        /**
        * This method is suppose to count the number of entries in the le
        */
        public static void count_entries() // note: this method does NOT have the correct return type or method parameters!
        {
        }
    }

    Keep working through the framework to build a more complete understanding of what the program is suppose to do. Notice what I'm doing:

    I'm describing in English/comments roughly what I want the program to do and where it should be done. At this point it isn't terribly important if you don't know how to do something in Java. If you know what parameters the methods should take and what they should return, code those in. If not, make a note to yourself. Once you have a framework start filling in the gaps. If you have questions about how to perform a particular task like reading from a file, try doing a Google search. If you still have questions, ask.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Wow. you guys are incredible. I really appreciate the time you have taken to helping me figure out this problem. I really like the layout provided above as well as the examples of the "Person" class. It is in a language i can understand. My teacher, unfortunately, is teaching his first class ever (mine) so his style is lacking, as supposed to a seasoned professor. I sat down with him this morning and talked out my problems i am having and my questions. He answered a few, but still left many holes (which I suppose is his way of "teaching" me) I have started working on the code, and now have a basic idea of what needs to happen (thanks to you). Here is what i have so far, and what i am taking notes on in his class. Where i am still struggling is HOW to implement the code to work together.
    Does Java code read top to bottom? or is it more priority reading?

    import java.util.*;
    import java.io.*;
     
    public class Perser {
     
    	File uniprot = new File ("uniprotFile.txt");
    	Scanner uniprotScanner = new Scanner (uniprot);
     
    	while (uniprotScanner.hasNextLine()){
    		String currentLine = uniprotScanner.nextLine();
    		String[] tokens = currentLine.split(" ");
    		if ( tokens [0].equals("AC")){
    			System.out.println(tokens[1]);
    		}
    		else if (tokens [0].equals("SQ")){
    			String sequenceLine = uniprotScanner.nextLine();
    			sequenceLine.replace(' ', '\0');
    		}
     
    	}
    }

    i realize that this code does not include a "Main" nor does it include other methods at all. So i was wondering if you could help me format this a little or maybe help me fill in the blanks a bit on the "Skeleton Code" you provided me with above

    Thanks again for all your help. you guys are really making this an easier process for me.

  9. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Need help with understanding a homework assignment, not asking for answers

    So one thing I'm noticing right away is you code will not compile/run (your code isn't inside of a method). I am a big fan of "incremental development", i.e. build and test often. This lets you test small sections so you know what changes you made work and which ones didn't. Starting off you may even go so far as to test build and run each individual statement, and later on you can test larger chunks (i.e. a few lines) of code together as you get more familiar with the language.

    Reading Java code is not completely a top-to-bottom process. Rather, the best way to read Java code is to break it up into chunks, and link the chunks together. Imagine a tree with the main trunk, which branches out into smaller branches before reaching the leaves. Start with the largest chunks and work your way down to the small ones (same idea holds when it comes time to actually write code: work from big ideas down to the details).

    For example, the largest chunk you have is the class declaration:

    public class Parser
    {
       // describes the Parser class
    }

    Everything inside of this class is associated somehow with the Parser class. If it wasn't, it wouldn't/shouldn't be in this class.

    Classes have 2 fundamental elements: methods, and fields. Personally I like to place fields towards the top of the class declaration and methods below them, though it's perfectly acceptable to do the opposite. You can also intermix the two, though this makes reading the class a more difficult most of the time.

    You don't have to initialize the fields when you declare them, some people do whenever they can and others avoid it whenever possible.

    public class SomeClass
    {
       // declare all your class fields here
       public static int some_int = 0;
     
       // declare all you class methods here
       public static void main(String[] args)
       {
       }
    }

    Here you already have something to test compile to make sure it works. If there's no compile errors you know you've done well. If there are, it's much easier to tell where the errors are.

    From this point, you can start splitting into each method's code block. These blocks tend to read much more linearly.

    // still inside of SomeClass, but the other code is omitted here for clarity.
    public static void main(String[] args)
    {
       Scanner reader = new Scanner(System.in);
     
       System.out.print("What is your name? ");
       String name = reader.nextLine();
     
       System.out.println("Hello, " + name);
       if(name.length() < 5)
       {
           System.out.println("You have a short name.");
       }
       else
       {
           System.out.println("Your name isn't so short.");
       }
    }

    The general rule of thumb is each section contained by a pair of curly braces ({ }) is a contained block and should be treated as such. For this reason I recommend always using curly braces around if/else statements, while loops, for loops, etc. These are separate blocks, even if they're only one line long.

    Are you unsure about how to declare a method?

    The main method in Java always has the same signature (there are variations in how it's written sometimes, but they all do the same thing):

    public static void main(String[] args)
    {
        // main method code goes between these two curly braces
    }

    You can essentially copy/paste this every time you need a main method in a class.

    To re-iterate again, start with a structure similar to the one I outlined above. It's not complete so you're welcome to copy/paste it as your starting point. Start with the comments. They may not do anything execution-wise, but they will help you organize your thoughts and will help you figure out what needs to be done.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Thank you again for the help (the old C++ forums i used were filled with self centered people, who refused to even provide insight on homework). Ok so i have changed the layout to the above example, and i think I have things in the right areas. I am confused on how the main should call the different methods.
    Is it
    args[1] = extract_info
    Sorry i know i am asking very basic coding questions, but I am brand new to the Java language all together.

    So tell me if this looks any better. It has an error saying that "uniprot can not be resolved to a variable" is that because i declared it outside of the method? should i move that back inside extract_info?

    import java.util.*;
    import java.io.*;
     
    public class Perser 
    {
    	    /**
    	    * This is the main method. It takes two command-line args, the uniProtFile and fastaFile. It uses these to parse out some information.
    	    */
    	    public static void main(String[] args)
    	    {
    	    	File uniprot = new File ("uniprotFile.txt");
    	        // the two file names are inside the array args
    	        // args[0] has the uniProtFile filename
    	        // args[1] has the fastaFile filename
    	    }
     
    	    /**
    	    * This method is suppose to extract the accession numbers and sequences
    	    */
    	    public static void extract_info() // note: this method does NOT have the correct return type or method parameters!
    	    {
    		    /**
    		    * This method is suppose to count the number of entries in the le
    		    */
    	    	Scanner uniprotScanner = new Scanner (uniprot);
     
    	    	while (uniprotScanner.hasNextLine()){
    	    		String currentLine = uniprotScanner.nextLine();
    	    		String[] tokens = currentLine.split(" ");
     
    	    		if ( tokens [0].equals("AC"))
    	    		{
    	    			System.out.println(tokens[1]);
    	    		}
    	    		else if (tokens [0].equals("SQ"))
    	    		{
    	    			String sequenceLine = uniprotScanner.nextLine();
    	    			sequenceLine.replace(' ', '0');
    	    		}
     
    	    	}
    	    }
     
    	    public static void count_entries() // note: this method does NOT have the correct return type or method parameters!
    	    {
     
    	    }
     
    }

  11. #10
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Quote Originally Posted by NewbieJavaProgrammer View Post
    It has an error saying that "uniprot can not be resolved to a variable" is that because i declared it outside of the method? should i move that back inside extract_info?
    Hit up your favorite search engine for "java scope" for details.

    You declared uniport inside the main method. That means uniport is only a valid variable name within the { and } of public static void main(String[] args). It looks to me like you need that variable in both methods. Perhaps it should be declared more class-wide than method specific. Take a peek at the Person class sample posted earlier. Take note that the variable myAge was declared outside of all methods, and is accessible in the constructors as well as the geter and setter methods.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Ah yes that makes alot of sense. So even though the methods are PUBLIC, the variables in side of each are still only used within their respectied method. Unless called by something outside?

  13. #12
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Variables are valid only within the scope for which they are declared. Looking again at the sample Person class, myAge was declared inside the class, outside of any method. That makes the variable usable from anywhere inside the class. On the other hand consider the variable age on the constructor. That variable is good only within the scope of the constructor. Consider the variable age in the setter method. Again this variable is local to the method only. Ignore the public, private, and protected keywords for now, and do some research on scope. There is plenty of existing information available if you just search a little bit.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Ok. So after a few hours of work (and several peoples advice) i have come to this new code:

    import java.util.*;
    import java.io.*;
     
    public class Perser 
    {
    	    /**
    	    * This is the main method. It takes two command-line args, the uniProtFile and fastaFile. It uses these to parse out some information.
    	    */
    	    public static void main(String[] args) throws IOException
    	    {	
    	    	String[][] extractedInfo = extract_info();
     
    	    	for(int i = 0; i < extractedInfo.length; i++)
    	    	{
    	    		extractedInfo[i][0]
    	    	}
     
    	        // the two file names are inside the array args
    	        // args[0] has the uniProtFile filename
    	        // args[1] has the fastaFile filename
     
    	    }
     
    	    public static void fileWriter() throws IOException
    	    {
    	    	BufferedWriter writtenFile = new BufferedWriter(new FileWriter("fastaFile.txt"));
    	    	writtenFile.write();
    	    }
     
     
     
    	    public static String[][] extract_info() throws IOException // note: this method does NOT have the correct return type or method parameters!
    	    {
    		    String[][] foo = new String[count_entries()][2];
    	    	File uniprot = new File ("uniprotFile.txt");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    	int i = 0;
     
    	    	while (uniprotScanner.hasNextLine())
    	    	{
    	    		String currentLine = uniprotScanner.nextLine();
    	    		String[] tokens = currentLine.split(" ");
     
    	    		if ( tokens [0].equals("AC"))
    	    		{
    	    			System.out.println(tokens[3]);
    	    			tokens[3] = foo[i][1];
    	    		}
    	    		else if (tokens [0].equals("SQ"))
    	    		{
    	    			String sequenceLine = uniprotScanner.nextLine();
    	    			sequenceLine.replace(' ', '\0');
    	    			foo[i][0];
    	    		}
    	    		else if (tokens [0].equals("//"))
    	    		{
    	    			i++;
    	    		}	    			    		
    	    	}
    	    	return foo;
    	    }
     
    	    public static int count_entries() throws IOException
    	    {
    	    	int entriesCount = 0;
    	    	File uniprot = new File ("uniprotFile.txt");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    while (uniprotScanner.hasNextLine())
    	    {
     
    	    	String currentLine = uniprotScanner.nextLine();
    	    	String[] tokens = currentLine.split(" ");
     
    	    	if (tokens [0].equals("//"))
    	    	{
    	    		entriesCount++;
    	    	}
     
    	    }
    	    return entriesCount;
    	    }
     }

    It does not compile yet (unfortunately) but I still need a few things:


    What it HAS:

    Correct method for counting entries
    Correct method for finding the AC and SQ

    What it NEEDS:

    A correct FOR loop to read through the 2D array (inside the main method)
    A file writer method (to save the FOR loop information in the main, to the file called "fastaFile.txt"

    Again i understand you can not GIVE me the code, but a nudge in the right direction or some knowledge and potential skeleton code would be greatly appreciated
    Also since i have not compiled this code yet i do not know 100% that my methods work, so if you notice anything in them that would pose a problem please let me know

    Thanks again, this community has been more the helpful and has really taught me more then my teacher has thus far.
    I appreciate you all, and hope to hear from you soon

  15. #14
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Quote Originally Posted by NewbieJavaProgrammer View Post
    Ok. So after a few hours of work (and several peoples advice) i have come to this new code:

    ......

    It does not compile yet (unfortunately) but I still need a few things:
    .....
    A word of advice: don't add anything at all until you can get the current code base to compile, else you risk adding good code to bad. I think that I speak for all in saying that we'd be more than happy to help you get this program to compile, but you'll have to tell us what errors you're currently seeing and indicate which line causes the errors.

  16. #15
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Need help with understanding a homework assignment, not asking for answers

    You said it's not compiling. Can you post the compiler output so we can see what the errors are?

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    I get an error in my For loop inside of my main

    for(int i = 0; i < extractedInfo.length; i++)
    	    	{
    	    		extractedInfo[i][0];
    	    	}

    it says: Syntax error, insert "AssignmentOperator Expression" to complete Expression
    I understand it is incomplete because it is not equaling anything, however the entire For statement as a whole I am confused on what to do. Because It needs to write the Data collected in the other two methods, and add them to the file "fastaFile.txt"

    But the process of doing that inside the for loop as well as adding it the file is a new concept to me. That is what I think I am needing advice on. The rest of it doesn't seem to actually have errors
    (Finally!)

    Thanks again all

  18. #17
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help with understanding a homework assignment, not asking for answers

    extractedInfo[i][0];
    That line does not really DO anything.

    If I had a HashMap full of keys to ArrayLists, I would first write code that would iterate the HashMap and println the keys to me.
    Once that would compile and run as expected, I would be confident in that part of the code.
    From there I would work on using the key to grab the ArrayList behind it, and possibly print out the ArrayList.toString() just to see that it was working.
    Then I would work on a loop that would iterate an ArrayList and println each element in the list. That can later be adapted to do something besides print each element, etc.
    Having seen your code I am sure you can get it to work.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Ok. so after reading a few posts online. I found a way to read the array and save into a file (at least i believe i did it correctly) but now i am receiving errors else where.

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Syntax error, insert "AssignmentOperator Expression" to complete Expression

    at Perser.extract_info(Perser.java:58)
    at Perser.main(Perser.java:12)

    which pertains to
    public static String[][] extract_info() throws IOException
    	    {
    		    String[][] foo = new String[count_entries()][2];
    	    	File uniprot = new File ("uniprotFile.txt");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    	int i = 0;
     
    	    	while (uniprotScanner.hasNextLine())
    	    	{
    	    		String currentLine = uniprotScanner.nextLine();
    	    		String[] tokens = currentLine.split(" ");
     
    	    		if ( tokens [0].equals("AC"))
    	    		{
    	    			System.out.println(tokens[3]);
    	    			tokens[3] = foo[i][1];
    	    		}
    	    		else if (tokens [0].equals("SQ"))
    	    		{
    	    			String sequenceLine = uniprotScanner.nextLine();
    	    			sequenceLine.replace(' ', '\0');
    	    			THIS LINE OF CODE-------> foo[i][0];
    	    		}
    	    		else if (tokens [0].equals("//"))
    	    		{
    	    			i++;
    	    		}	    			    		
    	    	}
    	    	return foo;
    	    }
    I think i am doing it correctly. the original assignment (in case you forgot) is to read a set of information and when i find the start "AC" to save the next set of information (being done in the first "IF" statement above) the next thing is to find when a line starts with SQ and save the following "sequence" (minus spaces, hence the sequenceLine.replace(' ','\0'); line) but after that is were the error happens.

    The next error refers to

    public static void main(String[] args) throws IOException
    	    {	
    	    	PrintWriter pr = new PrintWriter("fastaFile.txt");
    	    	THIS LINE OF CODE--------> String[][] extractedInfo = extract_info();
     
    	    	for(int i = 0; i < extractedInfo.length; i++)
    	    	{
    	    		for(int j = 0; j < 2; j++)
    	    		{
    	    			pr.println(extractedInfo[i][j]);
    	    		}
    	    		pr.close();
    	    	}
    This is my most recent change to my code in attempts to get it to compile. I think this is saving it to "fastaFile.txt" but again not sure if I am using the code correctly

    Any help would be greatly appreciated, I will post the entire program below so you can see how it works together

    import java.util.*;
    import java.io.*;
     
    public class Perser 
    {
    	    /**
    	    * This is the main method. It takes two command-line args, the uniProtFile and fastaFile. It uses these to parse out some information.
    	    */
    	    public static void main(String[] args) throws IOException
    	    {	
    	    	PrintWriter pr = new PrintWriter("fastaFile.txt");
    	    	String[][] extractedInfo = extract_info();
     
    	    	for(int i = 0; i < extractedInfo.length; i++)
    	    	{
    	    		for(int j = 0; j < 2; j++)
    	    		{
    	    			pr.println(extractedInfo[i][j]);
    	    		}
    	    		pr.close();
    	    	}
     
    	        // the two file names are inside the array args
    	        // args[0] has the uniProtFile filename
    	        // args[1] has the fastaFile filename
     
    	    }
     
    	    public static void fileWriter() throws IOException
    	    {
    	    	BufferedWriter writtenFile = new BufferedWriter(new FileWriter("fastaFile.txt"));
    	    	writtenFile.write();
    	    }
     
     
     
    	    public static String[][] extract_info() throws IOException // note: this method does NOT have the correct return type or method parameters!
    	    {
    		    String[][] foo = new String[count_entries()][2];
    	    	File uniprot = new File ("uniprotFile.txt");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    	int i = 0;
     
    	    	while (uniprotScanner.hasNextLine())
    	    	{
    	    		String currentLine = uniprotScanner.nextLine();
    	    		String[] tokens = currentLine.split(" ");
     
    	    		if ( tokens [0].equals("AC"))
    	    		{
    	    			System.out.println(tokens[3]);
    	    			tokens[3] = foo[i][1];
    	    		}
    	    		else if (tokens [0].equals("SQ"))
    	    		{
    	    			String sequenceLine = uniprotScanner.nextLine();
    	    			sequenceLine.replace(' ', '\0');
    	    			foo[i][0];
    	    		}
    	    		else if (tokens [0].equals("//"))
    	    		{
    	    			i++;
    	    		}	    			    		
    	    	}
    	    	return foo;
    	    }
     
    	    public static int count_entries() throws IOException
    	    {
    	    	int entriesCount = 0;
    	    	File uniprot = new File ("uniprotFile.txt");
    	    	Scanner uniprotScanner = new Scanner (uniprot);
    	    while (uniprotScanner.hasNextLine())
    	    {
     
    	    	String currentLine = uniprotScanner.nextLine();
    	    	String[] tokens = currentLine.split(" ");
     
    	    	if (tokens [0].equals("//"))
    	    	{
    	    		entriesCount++;
    	    	}
     
    	    }
    	    return entriesCount;
    	    }
     }

    Final note:
    I do not THINK i need to have a third method called "fileWriter" because of what I am attempting to do in my Main method. but correct me if I am wrong
    Thanks again for all the help. It is due by midnight tonight. So I will post again before the day is out.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    UPDATE: The code can run and terminate without errors: but no NEW file is created, so I believe the main problem is in the output located in the Main Method

  21. #20
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Need help with understanding a homework assignment, not asking for answers

    You're having the same issue as before:

    foo[i][0];

    This doesn't do anything. The compiler is telling you that. Either remove the line or modify it to do something (either assign to it or use it).

    One thing I noticed which you will probably eventually find but I thought I'd bring it up now to save you some time:

    if ( tokens [0].equals("AC"))
    	    		{
    	    			System.out.println(tokens[3]);
    	    			tokens[3] = foo[i][1];
    	    		}

    I think you're confusing the way to use the assignment operator. The correct syntax is:

    variable = value;

    This is incorrect:

    value = variable;

    side-note: I wouldn't name your array foo. It makes it unclear what this variable is used for. Try to pick a descriptive name which describes what it holds and/or is used for (for example info).

    edit:

    You don't need another method to write the output file. However, it's not incorrect to do so. It's something I would do personally because it makes your code more abstract and fits into the code re-use mentality in Java.

    You're also not extracting the filenames from the command line, you're hard-coding them into your program.

    The commandline args are put into the main method argument args. It's a simple string array which holds the args in order they were entered.

    Ex.:

    >java perser.java file1.txt file2.txt

    Then in your java code:

    public static void main(String[] args)
    {
        System.out.println("The first argument is: " + args[0]);
        System.out.println("The second argument is: " + args[1]);
    }

    Lastly, you've miss-spelled the class name. You have Perser.java, it's suppose to be Parser.java

    What do you mean no new file is being created? Is it empty? Or can you not find the file at all? I would recommend digging around your project folder to find it (your code seems to indicate it should have been created).
    Last edited by helloworld922; September 14th, 2012 at 07:21 PM.

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

    Default Re: Need help with understanding a homework assignment, not asking for answers

    Ex.:

    >java perser.java file1.txt file2.txt


    Then in your java code:

    public static void main(String[] args)
    {
    System.out.println("The first argument is: " + args[0]);
    System.out.println("The second argument is: " + args[1]);
    }
    Could you explain this a little more please. I am having trouble with this idea. Just don't get it.

    Also do i have to use that in my program? or and if so, how would I given the code i have?

    Also is there anything wrong with this segment of the code?
    else if (tokens [0].equals("SQ"))
    	    		{
    	    			String sequenceLine = uniprotScanner.nextLine();
    	    			sequenceLine.replace(' ', '\0');
    	    			//while(tokens [0] != "//")
    	    			System.out.println();
    	    			sequenceLine = fastaArray[i][0];
    	    		}
    And the above code only seems to pull one line of the sequence out. (besides what i have commented out, that is new code I am trying)
    how would i get that code to keep taking the lines of sequence until it hits "//"?

    Finally. when i run it it says it just <terminates> but doesnt SHOW a new file created in the Navigator on the left of Eclipse

  23. #22
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Need help with understanding a homework assignment, not asking for answers

    In my example I'm explaining how command-line arguments work. The assignment indicates that you're expected to get the file names from the command-line. The Java code I provided is just an example to show you how to access the command-line arguments passed to your program. You're right, all it does is print them out. You just need to replace your hard-coded filenames with the ones supplied by the command-line.

    Eclipse doesn't continuously monitor what files are in your project but they should be there in your filesystem. Right click on your project and click "refresh". Alternatively, open up Explorer (or whatever program you use to navigate the filesystem if you're not using Windows) and navigate to your project directory.

    So you want the code keep getting data until it reaches a // token?

    Try to write down on paper a step-by-step process of how you would do this by hand (be very verbose). If possible use the java control keywords and avoid other control-like keywords.

    Ex. (easy to code):

    while the current token command isn't //:
    ... do something (this is for you to figure out)

    Ex. (not so easy to code):

    keep adding tokens to the fastaArray until we reach the // token command

  24. #23
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    491
    Thanks
    8
    Thanked 47 Times in 45 Posts

    Default Re: Need help with understanding a homework assignment, not asking for answers

    This thread has been cross posted here:

    http://www.java-forums.org/new-java/63021-2-dimensional-array-write-error-file.html

    Although cross posting is allowed, for everyone's benefit, please read:

    Java Programming Forums Cross Posting Rules

    The Problems With Cross Posting
    db


Similar Threads

  1. Replies: 3
    Last Post: July 8th, 2012, 03:44 PM
  2. Yes or No answers,
    By tyb97 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: September 18th, 2011, 05:57 PM
  3. Homework assignment (beginner)
    By z3ohyr84 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: May 30th, 2011, 01:32 PM
  4. Array Homework assignment
    By lich0802 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 27th, 2011, 07:17 PM
  5. Is My answers correct??
    By Java.Coder() in forum What's Wrong With My Code?
    Replies: 6
    Last Post: December 28th, 2010, 05:22 AM

Tags for this Thread