I have 2 arrays that are in a while loop each. I have declared the array ouside of the main, declaring it 'public static'. I want to use the values store in the array outside of the while loop, but I can't seem to do it. May I know how to use the array with the stored value outside of the while loop?

There are a few possible problems I can imagine here, but I don't know which one it'll be without seeing the code.

One is something like this:

public class ThisClass
{
  public static int intArray[3];
  public boolead theMoonIsMadeofGreenCheese = true;

  public static void main (String[] args)
  {
    while (theMoonIsMadeOfGreenCheese)
    {
       public static intArray[] = {0,1,2,3};

       // oops! we've shadowed the other intArray! this is a different one
  
       
    }

    int i = intArray[1];
    // error! not declared...
  }

}

That's one thing it MIGHT be. If that's not it, give us teh codez and we'll see what it actually is.

Edited 6 Years Ago by jon.kiparsky: n/a

Have you defined a second array with the same name inside the loop, hiding the public one?

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MatchApplet extends JApplet {


//  TextField seq1in = new TextField("HEAGAWGHEE");
//  TextField seq2in = new TextField("PAWHEAE");

	TextArea outputArea;
	JButton button;
	JButton reset;

	JTextField tF1;
	JTextField tF2;

	JLabel l1;
	JLabel l2;

	String s1;
	String s2;
	
	public static BufferedReader input, input2;	
	[B]public static String[] store = new String [10000];
	public static String[] store2 = new String [10000];
	public static int z = 0;
	public static int z2 = 0;[/B]	


	public static void main(String[] args)
	{
		//Application for program
  		Frame f = new Frame();
  		f.addWindowListener(new java.awt.event.WindowAdapter()
  		{
       	public void windowClosing(java.awt.event.WindowEvent e)
       	{
       	System.exit(0);
      	};
     	});

  		MatchApplet ut = new MatchApplet();
  		ut.setSize(900,900); // same size as defined in the HTML APPLET
  		f.add(ut);
  		f.pack();
  		ut.init();
  		f.setSize(900,900 + 100); // add 20, seems enough for the Frame title,
  		f.show();
  		
  		//end of application for program
  		
  		
  		
  		int j=0, h=0, i=0;
		
		String[] counter3 = new String [10000];	//stores 3rd tokens of first original extracted file
		String[] counter4 = new String [10000];	//stores 4th tokens of first original extracted file
		String[] counter1 = new String [10000];	//stores both 3rd and 4th tokens of first original extracted file
		String[] counter5 = new String [10000];	//stores 3rd tokens of second original extracted file
		String[] counter6 = new String [10000];	//stores 4th tokens of second original extracted file 
		String[] counter7 = new String [10000]; //stores both 3rd and 4th tokens of second original extracted file	
		
		
	  
	try{	//extract sequence 1 from txt file
      
      input = new BufferedReader(new FileReader( new File("D:\\project1\\Dynamic Programming\\Alignment Algorithms\\Sequence Testing\\1a00.gz.txt") ) );	// input specified file
      String extract;
      while ( ( extract = input.readLine() ) != null ) 			//reading specified file
      {
      	
      	if ((extract.trim().startsWith("ATOM") && !extract.trim().endsWith("H"))) 		//extract lines that starts with ATOM AND end with anything but H
      	{
			StringTokenizer s = new StringTokenizer(extract," ");		//String tokenizer
      		int counter=0;
      
      	while(s.hasMoreTokens())
      	{
      	 	
      		String ss = s.nextToken();
     		counter++;
      
      		if (counter == 3) 						//extracts 3rd tokens of each line	
 			counter3[j] = ss;			
      												     		
			if(counter == 4)						//extracts 4th tokens of each line
			counter4[h] = ss;     		
      		
      	}// end of while(s.hasMoreTokens())

		    counter1[i] = counter3[j] +"\t"+ counter4[h];    

		    if (counter1[i].trim().startsWith("CA")) 
		    {
	
      		StringTokenizer a = new StringTokenizer(counter1[i],"\t");
      		int amino=0;
      		
      			while(a.hasMoreTokens())
      			{
      	 		
      			String aa = a.nextToken();
     			amino++;
     		
     				if (amino == 2)
     				{	   		
     					
      					if(aa.trim().startsWith("ALA"))
      					store [z] = "A";  			
     					if(aa.trim().startsWith("ARG"))
      		    		         store [z] = "R";
      					if(aa.trim().startsWith("ASN"))
      	      			         store [z] = "N";
      					if(aa.trim().startsWith("ASP"))
      					store [z] = "D";
      					if(aa.trim().startsWith("CYS"))
      					store [z] = "C";
      					if(aa.trim().startsWith("GLN"))
      					store [z] = "Q";      			
      					if(aa.trim().startsWith("GLU"))
      					store [z] = "E";
      					if(aa.trim().startsWith("GLY"))
      					store [z] = "G";    
      					if(aa.trim().startsWith("HIS"))
      					store [z] = "H";      			
      					if(aa.trim().startsWith("ILE"))
      					store [z] = "I";
      					if(aa.trim().startsWith("LEU"))
       					store [z] = "L";     			
      					if(aa.trim().startsWith("LYS"))
        				store [z] = "K";    			
      					if(aa.trim().startsWith("MET"))
          				store [z] = "M";  			
      					if(aa.trim().startsWith("PHE"))
         				store [z] = "F";   			      			
      					if(aa.trim().startsWith("PRO"))
        				store [z] = "P";    			
      					if(aa.trim().startsWith("SER"))
        				store [z] = "S";    			
      					if(aa.trim().startsWith("THR"))
        				store [z] = "T";    			
      					if(aa.trim().startsWith("TRP"))
        				store [z] = "W";    			
      					if(aa.trim().startsWith("TYR"))
        				store [z] = "Y";    			
      					if(aa.trim().startsWith("VAL"))
      					store [z] = "V"; 	
      			
      		
      					//System.out.print(store[z]);
      					
				
					}//end of if (amino == 2)
					
		
				}//end of while(a.hasMoreTokens())
		
      		
      		[B]}//end of if (counter1[i].trim().startsWith("CA"))[/B]	    	
		
														
      	}//end of if ((extract.trim().startsWith("ATOM") && !extract.trim().endsWith("H")))
      	    			
 	    			
      }//end of while ( ( extract = input.readLine() ) != null )    
      		
			input.close();
			
	}catch( IOException ioException ) {}

The array in the while loop can't be used outside after this sentence:
}//end of if (counter1.trim().startsWith("CA")).
I have also bold the declaration part, it is outside of the main loop.

Edited 6 Years Ago by Sunshineserene: n/a

Good gravy. What a mess.

What do you mean when you say it can't be used? All you've done with it here is to assign a one-character string to the first place - there's a lot of unused array here, is that the problem?
(did you mean to increment z inthe while loop?)

I want to use the array with the stored values outside of the main class. How do I do that?

You should have no trouble using it outside of the main class. It's public, so you can just set and read the values to your heart's content.
Of course, it's static, which means that if you're outside of an instance of MatchArray, you have to access it as MatchArray.store[], not by the name of some particular instance.

Have you dealt with the z problem yet?

Did you read my previous post? You have an index (z) which is clearly meant to be incremented, but isn't incremented. This is why you don't have any values for indexes >0.

So if I shouldn't have any problems using the array with the stored value outside anywhere, does it mean that the main problem causing me to have errors is the index z?

Depends, but if you're trying to read values other than store[0], you're getting null. That may not be what you're looking for.

As to problems reading the array outside the class, no, shouldn't be a problem, as long as you're aware that it's a static, and has to be called through the class, not through an object.

So can I implement the index z using for loop? I tried, but it's not working.
And the array in while loop is actually within the main, but when I call the array in the init() method, it cannot be done. However both main and init() are in the same class.

All I know is, you've got a while loop that overwrites store[0] a bazillion times. That's probably wrong. I don't know what your problem in init is - you should have access to store anywhere in this class.
init() sounds like you're running this as an applet? If so, you probably haven't run main() - is there any data in store when you try to access it?

I'm really shooting in the dark here. What, precisely, is the problem? What error are you seeing? If the compiler is reporting a problem, what is it? You've jumped through three different issues so far - can't refer to the array outside of the while loop (local scope, sounds like a shadowing problem), then you want to call it outside of the class (okay, static field, use WhateverThisClassIsCalled.store[] to refer to it) and now you're having trouble in another method in the class. Which is the problem you're actually trying to solve?

Okay I'm so sorry. The array store and store2 itself have stored values, which is the step in the while loop. I tried testing using System.out.println(store[z]); and System.out.println(store2[z2]); right after thw whole chunk of 'if' statements, and my output is correct. However, when I put the System.out.println statement after the 'if' statement (the 'while' loop is in the 'if' statement) for testing, the output is all wrong already. In another words, the results done in the while loop cannot be shown anywhere outside. This is the problem I'm having now. I need to use the array with the stored values outside of the while statement, but I don't know what has gone wrong.

Edited 6 Years Ago by Sunshineserene: n/a

Just for giggles, try putting in a z++ in that while loop, so you're actually populating the array. Then, after the while loop terminates, iterate the array by whatever means you prefer and see if there are values in it. I don't care if you use a while or a for or what. Simplest and best for cranking through an array is

for (String s:store)  
  println(s);

If that prints out a ton of lines, and the lines look like they correspond to your data, then you've got values in the array. In that case, you should have no further trouble.

The output of the first file should be this:
VLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYRMHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPYTQRFFESFGDLSTPDAVMGNPKVKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFGKEFTPPVQAAYQKVVAGVANALAHKYHVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYRMHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPYTQRFFESFGDLSTPDAVMGNPKVKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFGKEFTPPVQAAYQKVVAGVANALAHKYH

The output of the second file should be this:
MKRESHKHAEQARRNRLAVALHELASLIPAEWKQQNVSAAPSKATTVEAACRYIRHLQQNGSTMKRESHKHAEQARRNRLAVALHELASLIPAEWKQQNVSAAPSKATTVEAACRYIRHLQQNGST

However, when I use the array out of the 'if' statement, I can't access the output I want anymore. It would be null.

It would be null.

Can you show us the code and/or exception for that?
What variable is the "it"?

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MatchApplet extends JApplet {


//  TextField seq1in = new TextField("HEAGAWGHEE");
//  TextField seq2in = new TextField("PAWHEAE");

	TextArea outputArea;
	JButton button;
	JButton reset;

	JTextField tF1;
	JTextField tF2;

	JLabel l1;
	JLabel l2;

	String s1;
	String s2;

	public static BufferedReader input, input2;
	public static String[] store = new String [1];
	public static String store2;
	public static int z = 0;
	public static int z2 = 0;



	public static void main(String[] args)
	{
		//Application for program
  		Frame f = new Frame();
  		f.addWindowListener(new java.awt.event.WindowAdapter()
  		{
       	public void windowClosing(java.awt.event.WindowEvent e)
       	{
       	System.exit(0);
      	};
     	});

  		MatchApplet ut = new MatchApplet();
  		ut.setSize(900,900); // same size as defined in the HTML APPLET
  		f.add(ut);
  		f.pack();
  		ut.init();
  		f.setSize(900,900 + 100); // add 20, seems enough for the Frame title,
  		f.show();

  		//end of application for program



  		int j=0, h=0, i=0;

		String[] counter3 = new String [10000];	//stores 3rd tokens of first original extracted file
		String[] counter4 = new String [10000];	//stores 4th tokens of first original extracted file
		String[] counter1 = new String [10000];	//stores both 3rd and 4th tokens of first original extracted file
		String[] counter5 = new String [10000];	//stores 3rd tokens of second original extracted file
		String[] counter6 = new String [10000];	//stores 4th tokens of second original extracted file
		String[] counter7 = new String [10000]; //stores both 3rd and 4th tokens of second original extracted file



	try{	//extract sequence 1 from txt file

      input = new BufferedReader(new FileReader( new File("C:\\Users\\Serene\\Documents\\Major Project\\DP\\1a00.gz.txt") ) );	// input specified file
      String extract;
      while ( ( extract = input.readLine() ) != null ) 			//reading specified file
      {

      	if ((extract.trim().startsWith("ATOM") && !extract.trim().endsWith("H"))) 		//extract lines that starts with ATOM AND end with anything but H
      	{
			StringTokenizer s = new StringTokenizer(extract," ");		//String tokenizer
      		int counter=0;

      	while(s.hasMoreTokens())
      	{

      		String ss = s.nextToken();
     		counter++;

      		if (counter == 3) 						//extracts 3rd tokens of each line
 			counter3[j] = ss;

			if(counter == 4)						//extracts 4th tokens of each line
			counter4[h] = ss;

      	}// end of while(s.hasMoreTokens())

		    counter1[i] = counter3[j] +"\t"+ counter4[h];

		    if (counter1[i].trim().startsWith("CA"))
		    {

      		StringTokenizer a = new StringTokenizer(counter1[i],"\t");
      		int amino=0;

      			while(a.hasMoreTokens())
      			{

      			String aa = a.nextToken();
     			amino++;

     				if (amino == 2)
     				{

      					if(aa.trim().startsWith("ALA"))
      					store [z] = "A";
     					if(aa.trim().startsWith("ARG"))
      		    		store [z] = "R";
      					if(aa.trim().startsWith("ASN"))
      	      			store [z] = "N";
      					if(aa.trim().startsWith("ASP"))
      					store [z] = "D";
      					if(aa.trim().startsWith("CYS"))
      					store [z] = "C";
      					if(aa.trim().startsWith("GLN"))
      					store [z] = "Q";
      					if(aa.trim().startsWith("GLU"))
      					store [z] = "E";
      					if(aa.trim().startsWith("GLY"))
      					store [z] = "G";
      					if(aa.trim().startsWith("HIS"))
      					store [z] = "H";
      					if(aa.trim().startsWith("ILE"))
      					store [z] = "I";
      					if(aa.trim().startsWith("LEU"))
       					store [z] = "L";
      					if(aa.trim().startsWith("LYS"))
        				store [z] = "K";
      					if(aa.trim().startsWith("MET"))
          				store [z] = "M";
      					if(aa.trim().startsWith("PHE"))
         				store [z] = "F";
      					if(aa.trim().startsWith("PRO"))
        				store [z] = "P";
      					if(aa.trim().startsWith("SER"))
        				store [z] = "S";
      					if(aa.trim().startsWith("THR"))
        				store [z] = "T";
      					if(aa.trim().startsWith("TRP"))
        				store [z] = "W";
      					if(aa.trim().startsWith("TYR"))
        				store [z] = "Y";
      					if(aa.trim().startsWith("VAL"))
      					store [z] = "V";


      					System.out.print(store[z]);


					}//end of if (amino == 2)


				}//end of while(a.hasMoreTokens())


      		}//end of if (counter1[i].trim().startsWith("CA"))


      	}//end of if ((extract.trim().startsWith("ATOM") && !extract.trim().endsWith("H")))


      }//end of while ( ( extract = input.readLine() ) != null )

			input.close();

	}catch( IOException ioException ) {}



	System.out.println("\n");




	try{	//extracting sequence 2 from txt file

      input2 = new BufferedReader(new FileReader( new File("C:\\Users\\Serene\\Documents\\Major Project\\DP\\1a0a.gz.txt") ) );	// input specified file
      String extract2;
      while ( ( extract2 = input2.readLine() ) != null ) 			//reading specified file
      {

      	if ((extract2.trim().startsWith("ATOM") && !extract2.trim().endsWith("H"))) 		//extract lines that starts with ATOM AND end with anything but H
      	{
			StringTokenizer s2 = new StringTokenizer(extract2," ");		//String tokenizer
      		int counter2=0;

      	while(s2.hasMoreTokens())
      	{

      		String ss2 = s2.nextToken();
     		counter2++;

      		if (counter2 == 3) 						//extracts 3rd tokens of each line
 			counter5[j] = ss2;

			if(counter2 == 4)						//extracts 4th tokens of each line
			counter6[h] = ss2;

      	}// end of while(s.hasMoreTokens())

		    counter7[i] = counter5[j] +"\t"+ counter6[h];

		    if (counter7[i].trim().startsWith("CA"))
		    {

      		StringTokenizer a2 = new StringTokenizer(counter7[i],"\t");
      		int amino2=0;

      			while(a2.hasMoreTokens())
      			{

      			String aa2 = a2.nextToken();
     			amino2++;


     				if (amino2 == 2)
     				{

      					if(aa2.trim().startsWith("ALA"))
      					store2  = "A";
     					if(aa2.trim().startsWith("ARG"))
      		    		store2  = "R";
      					if(aa2.trim().startsWith("ASN"))
      	      			store2  = "N";
      					if(aa2.trim().startsWith("ASP"))
      					store2  = "D";
      					if(aa2.trim().startsWith("CYS"))
      					store2  = "C";
      					if(aa2.trim().startsWith("GLN"))
      					store2  = "Q";
      					if(aa2.trim().startsWith("GLU"))
      					store2  = "E";
      					if(aa2.trim().startsWith("GLY"))
      					store2  = "G";
      					if(aa2.trim().startsWith("HIS"))
      					store2  = "H";
      					if(aa2.trim().startsWith("ILE"))
      					store2  = "I";
      					if(aa2.trim().startsWith("LEU"))
       					store2  = "L";
      					if(aa2.trim().startsWith("LYS"))
        				store2  = "K";
      					if(aa2.trim().startsWith("MET"))
          				store2  = "M";
      					if(aa2.trim().startsWith("PHE"))
         				store2  = "F";
      					if(aa2.trim().startsWith("PRO"))
        				store2  = "P";
      					if(aa2.trim().startsWith("SER"))
        				store2  = "S";
      					if(aa2.trim().startsWith("THR"))
        				store2  = "T";
      					if(aa2.trim().startsWith("TRP"))
        				store2  = "W";
      					if(aa2.trim().startsWith("TYR"))
        				store2  = "Y";
      					if(aa2.trim().startsWith("VAL"))
      					store2  = "V";


						System.out.print(store2);


					}//end of if (amino2 == 2)


				}//end of while(a2.hasMoreTokens())


      		}//end of if (counter7[i].trim().startsWith("CA"))


      	}//end of if ((extract2.trim().startsWith("ATOM") && !extract2.trim().endsWith("H")))


      }//end of while ( ( extract2 = input2.readLine() ) != null )

			input2.close();

	}catch( IOException ioException ) {}



	}//end of public static void main(String[] args)



  public void init() {

		Container c = getContentPane();
		c.setLayout(new FlowLayout());

		outputArea = new TextArea(40,110);
		Font font = new Font("Courier", Font.PLAIN, 12);
		outputArea.setFont(font);
		outputArea.setEditable(false);

//		button = new JButton("Compute alignment");
//		reset = new JButton(" Reset ");

		tF1 = new JTextField("HEAGAWGHEE");
		tF2 = new JTextField("PAWHEAE");

		l1 = new JLabel("Sequence 1:");
		l2 = new JLabel("Sequence 2:");


		c.add(l1);
		c.add(tF1);
		c.add(l2);
		c.add(tF2);
//		c.add(button);
//		c.add(reset);
		c.add(outputArea);


	final Substitution sub = new Blosum50();
//	button.addActionListener(new ActionListener()
//	{
//		public void actionPerformed(ActionEvent e)
//		{

		s1 += tF1.getText();
		s2 += tF2.getText();
		Output out = new Output ()
		{
	  		public void print(String s)
	  		{ outputArea.append(s); }

	  		public void println(String s)
	  		{ outputArea.append(s); outputArea.append("\n"); }

	  		public void println()
	  		{ outputArea.append("\n"); }
		};

	outputArea.setText("");
      (new NW      (sub, 8,     s1, s2)).domatch(out, "GLOBAL ALIGNMENT");
      (new SW      (sub, 8,     s1, s2)).domatch(out, "LOCAL ALIGNMENT");
//		}
//	});


  }//end of init()
}//end of class




// The class of substitution (scoring) matrices

abstract class Substitution {
  public int[][] score;

  void buildscore(String residues, int[][] residuescores) {
    // Allow lowercase and uppercase residues (ASCII code <= 127):
    score = new int[127][127];
    for (int i=0; i<residues.length(); i++) {
      char res1 = residues.charAt(i);
      for (int j=0; j<=i; j++) {
        char res2 = residues.charAt(j);
        score[res1][res2] = score[res2][res1]
	  = score[res1][res2+32] = score[res2+32][res1]
	  = score[res1+32][res2] = score[res2][res1+32]
	  = score[res1+32][res2+32] = score[res2+32][res1+32]
	  = residuescores[i][j];
      }
    }
  }

  abstract public String getResidues();
}


// The BLOSUM50 substitution matrix for amino acids (Durbin et al, p 16)

class Blosum50 extends Substitution {

  private String residues = "ARNDCQEGHILKMFPSTWYV";

  public String getResidues()
  { return residues; }

  private int[][] residuescores =
            /* A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V */
  { /* A */ {  5                                                          },
    /* R */ { -2, 7                                                       },
    /* N */ { -1,-1, 7                                                    },
    /* D */ { -2,-2, 2, 8                                                 },
    /* C */ { -1,-4,-2,-4,13                                              },
    /* Q */ { -1, 1, 0, 0,-3, 7                                           },
    /* E */ { -1, 0, 0, 2,-3, 2, 6                                        },
    /* G */ {  0,-3, 0,-1,-3,-2,-3, 8                                     },
    /* H */ { -2, 0, 1,-1,-3, 1, 0,-2,10                                  },
    /* I */ { -1,-4,-3,-4,-2,-3,-4,-4,-4, 5                               },
    /* L */ { -2,-3,-4,-4,-2,-2,-3,-4,-3, 2, 5                            },
    /* K */ { -1, 3, 0,-1,-3, 2, 1,-2, 0,-3,-3, 6                         },
    /* M */ { -1,-2,-2,-4,-2, 0,-2,-3,-1, 2, 3,-2, 7                      },
    /* F */ { -3,-3,-4,-5,-2,-4,-3,-4,-1, 0, 1,-4, 0, 8                   },
    /* P */ { -1,-3,-2,-1,-4,-1,-1,-2,-2,-3,-4,-1,-3,-4,10                },
    /* S */ {  1,-1, 1, 0,-1, 0,-1, 0,-1,-3,-3, 0,-2,-3,-1, 5             },
    /* T */ {  0,-1, 0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1, 2, 5          },
    /* W */ { -3,-3,-4,-5,-5,-1,-3,-3,-3,-3,-2,-3,-1, 1,-4,-4,-3,15       },
    /* Y */ { -2,-1,-2,-3,-3,-1,-2,-3, 2,-1,-1,-2, 0, 4,-3,-2,-2, 2, 8    },
    /* V */ {  0,-3,-3,-4,-1,-3,-3,-4,-4, 4, 1,-3, 1,-1,-3,-2, 0,-3,-1, 5 }
            /* A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V */
  };

  public Blosum50()
  { buildscore(residues, residuescores); }
}



// Pairwise sequence alignment

abstract class Align {
  Substitution sub;             // substitution matrix
  int d;                        // gap cost
  String seq1, seq2;            // the sequences
  int n, m;                     // their lengths
  Traceback B0;                 // the starting point of the traceback

  final static int NegInf = Integer.MIN_VALUE/2; // negative infinity

  public Align(Substitution sub, int d, String seq1, String seq2) {
    this.sub = sub;
    this.seq1 = strip(seq1); this.seq2 = strip(seq2);
    this.d = d;
    this.n = this.seq1.length(); this.m = this.seq2.length();
  }

  public String strip(String s) {
    boolean[] valid = new boolean[127];
    String residues = sub.getResidues();
    for (int i=0; i<residues.length(); i++) {
      char c = residues.charAt(i);
      if (c < 96)
	valid[c] = valid[c+32] = true;
      else
	valid[c-32] = valid[c] = true;
    }
    StringBuffer res = new StringBuffer(s.length());
    for (int i=0; i<s.length(); i++)
      if (valid[s.charAt(i)])
	res.append(s.charAt(i));
    return res.toString();
  }

  // Return two-element array containing an alignment with maximal score

  public String[] getMatch() {
    StringBuffer res1 = new StringBuffer();
    StringBuffer res2 = new StringBuffer();
    Traceback tb = B0;
    int i = tb.i, j = tb.j;
    while ((tb = next(tb)) != null) {
      if (i == tb.i)
        res1.append('-');
      else
        res1.append(seq1.charAt(i-1));
      if (j == tb.j)
        res2.append('-');
      else
        res2.append(seq2.charAt(j-1));
      i = tb.i; j = tb.j;
    }
    String[] res = { res1.reverse().toString(), res2.reverse().toString() };
    return res;
  }

  public String fmtscore(int val) {
    if (val < NegInf/2)
      return "-Inf";
    else
      return Integer.toString(val);
  }

  // Print the score, the F matrix, and the alignment
  public void domatch(Output out, String msg, boolean udskrivF) {
    out.println(msg + ":");
    out.println("Score = " + getScore());
    if (udskrivF) {
      out.println("The F matrix:");
      printf(out);
    }
    out.println("An optimal alignment:");
    String[] match = getMatch();
    out.println(match[0]);
    out.println(match[1]);
    out.println();
  }

  public void domatch(Output out, String msg)
  { domatch(out, msg, true); }

  // Get the next state in the traceback
  public Traceback next(Traceback tb)
  { return tb; }                // dummy implementation for the `smart' algs.

  // Return the score of the best alignment
  public abstract int getScore();

  // Print the matrix (matrices) used to compute the alignment
  public abstract void printf(Output out);

  // Auxiliary functions
  static int max(int x1, int x2)
  { return (x1 > x2 ? x1 : x2); }

  static int max(int x1, int x2, int x3)
  { return max(x1, max(x2, x3)); }

  static int max(int x1, int x2, int x3, int x4)
  { return max(max(x1, x2), max(x3, x4)); }

  static String padLeft(String s, int width) {
    int filler = width - s.length();
    if (filler > 0) {           // and therefore width > 0
      StringBuffer res = new StringBuffer(width);
      for (int i=0; i<filler; i++)
        res.append(' ');
      return res.append(s).toString();
    } else
      return s;
  }
}


// Alignment with simple gap costs

abstract class AlignSimple extends Align {
  int[][] F;                    // the matrix used to compute the alignment
  Traceback2[][] B;             // the traceback matrix

  public AlignSimple(Substitution sub, int d, String seq1, String seq2) {
    super(sub, d, seq1, seq2);
    F = new int[n+1][m+1];
    B = new Traceback2[n+1][m+1];
  }

  public Traceback next(Traceback tb) {
    Traceback2 tb2 = (Traceback2)tb;
    return B[tb2.i][tb2.j];
  }

  public int getScore()
  { return F[B0.i][B0.j]; }

  public void printf(Output out) {
    for (int j=0; j<=m; j++) {
      for (int i=0; i<F.length; i++)
	out.print(padLeft(fmtscore(F[i][j]), 5));
      out.println();
    }
  }
}


// Traceback objects

abstract class Traceback {
  int i, j;                     // absolute coordinates
}


// Traceback2 objects for simple gap costs

class Traceback2 extends Traceback {
  public Traceback2(int i, int j)
  { this.i = i; this.j = j; }
}


// Auxiliary classes for output

abstract class Output {
  public abstract void print(String s);
  public abstract void println(String s);
  public abstract void println();
}

class SystemOut extends Output {
  public void print(String s)
  { System.out.print(s); }

  public void println(String s)
  { System.out.println(s); }

  public void println()
  { System.out.println(); }
}


// Global alignment with the Needleman-Wunsch algorithm (simple gap costs)

class NW extends AlignSimple {

  public NW(Substitution sub, int d, String sq1, String sq2) {
    super(sub, d, sq1, sq2);
    int n = this.n, m = this.m;
    int[][] score = sub.score;
    for (int i=1; i<=n; i++) {
      F[i][0] = -d * i;
      B[i][0] = new Traceback2(i-1, 0);
    }
    for (int j=1; j<=m; j++) {
      F[0][j] = -d * j;
      B[0][j] = new Traceback2(0, j-1);
    }
    for (int i=1; i<=n; i++)
      for (int j=1; j<=m; j++) {
        int s = score[seq1.charAt(i-1)][seq2.charAt(j-1)];
        int val = max(F[i-1][j-1]+s, F[i-1][j]-d, F[i][j-1]-d);
        F[i][j] = val;
        if (val == F[i-1][j-1]+s)
          B[i][j] = new Traceback2(i-1, j-1);
        else if (val == F[i-1][j]-d)
          B[i][j] = new Traceback2(i-1, j);
        else if (val == F[i][j-1]-d)
          B[i][j] = new Traceback2(i, j-1);
        else
          throw new Error("NW 1");
      }
    B0 = new Traceback2(n, m);
  }
}


// Local alignment with the Smith-Waterman algorithm (simple gap costs)

class SW extends AlignSimple {
  public SW(Substitution sub, int d, String sq1, String sq2) {
    super(sub, d, sq1, sq2);
    int n = this.n, m = this.m;
    int[][] score = sub.score;
    int maxi = n, maxj = m;
    int maxval = NegInf;
    for (int i=1; i<=n; i++)
      for (int j=1; j<=m; j++) {
        int s = score[seq1.charAt(i-1)][seq2.charAt(j-1)];
        int val = max(0, F[i-1][j-1]+s, F[i-1][j]-d, F[i][j-1]-d);
        F[i][j] = val;
        if (val == 0)
          B[i][j] = null;
        else if (val == F[i-1][j-1]+s)
          B[i][j] = new Traceback2(i-1, j-1);
        else if (val == F[i-1][j]-d)
          B[i][j] = new Traceback2(i-1, j);
        else if (val == F[i][j-1]-d)
          B[i][j] = new Traceback2(i, j-1);
        else
          throw new Error("SW 1");
        if (val > maxval) {
          maxval = val;
          maxi = i; maxj = j;
        }
      }
    B0 = new Traceback2(maxi, maxj);
  }
}

This is the codes. I'm doing an algorithm. The 'it' I'm referring to is the array.

The array is store[z] and actually store2[z2], but now for this code I'm testing only store[z]. From the codes, you see store[z] in a while loop, and this while loop is actually in a 'if' loop. When I test the output by printing it after the 'if' loop, the output is wrong alr. It's not the correct output.

I can't help noticing that you still haven't incremented your counter in that loop (the one running from 103-150 or so)
That means you still have an array called store[] which has the following contents:
store[0] = the single character string corresponding to the last token of whatever it is you're iterating over with StringTokenizer a
store[1 - 9999] = null

You're getting a lot of screen output with the print statement in that loop, but none of it is staying in memory. Again - is this what you mean to do? If so, why do you declare an array of 10000 strings to hold a single character?

Okay, I have corrected it, and I have incremented the z for everytime it is going to loop it. Then I put it in a for loop to print out the output. I have also store the array into a variable. Now the only problem is how do I use the variable out of the main loop and use it in the init() function?

problem is how do I use the variable out of the main loop and use it in the init() method

Define the variable as a class variable and all methods in the class will be able to use it.

Edited 6 Years Ago by NormR1: n/a

How do you define as a class variable? Hmmm, now the problem I'm facing is, I declared all my arrays and variables outside the public static void main. Then within my main, I did the calculations and stuff that I need, and I assigned the output of the array into the variable. However, when I call the variables in the init() function, it is empty. I troubleshoot the program, and I realised the variables in the init() is actually null, because it uses the variables I declared initially outside the main loop. Meaning, the variables with the stored values in the main function is not brought into the init() function. So now I wanna know how do I transfer it into the init() function. (:

A class variable is aso known as a "field" of the class. It's a property of either each object of the type defined by a class (an instance field) or of all members of the class collectively (a static field).

When you declare a variable "outside the public static void main", as you say, you are declaring a class field. When you declare a variable within a method (such as main, or init) you're declaring it within a local scope. If a variable is declared within a method, it only lasts as long as that particular call of that particular method does, it vanished as soon as that method returns. Method variables are not available to any other objects or methods, unless they are passed in a method call. (Okay, inheritance complicates that a little, but you're not using any inheritance, so don't worry about it now)

If you had declared store within the context of main(), or init(), the only way to get that array anywhere else would have been to pass it to some other method as a parameter or to write it to a class field. But you didn't do that, so you do have access to it.

In the code that you posted earlier in this thread, store[] was declared as a static array of Strings, and it's a class field of your class MatchApplet. What all this means is, you should not be having any trouble getting access to store[] in this class, and that suggests to me that this is a very minor syntax error and not a structural issue, as you suggest in your last post.

Now, having looked again at the code you posted before I see this, which I missed before:

StringTokenizer a = new StringTokenizer(counter1[i],"\t");
      		int amino=0;
      		
      			while(a.hasMoreTokens())
      			{
      	 		
      			String aa = a.nextToken();
     			amino++;
     		
     				if (amino == 2)
     				{
      					if(aa.trim().startsWith("ALA"))
      					store [z] = "A";  			
       					[snip...]
      					if(aa.trim().startsWith("VAL"))
      					store [z] = "V"; 	
					}//end of if (amino == 2)
						
				}//end of while(a.hasMoreTokens())

Again, you're getting tangled up and writing bizarre and senseless code. This is only looking at the String that's returned by nextToken() on the off chance that it's exactly the third one in whatever structure you're iterating over. Otherwise, amino!=2, so it SKIPS THE DAMNED ASSINGMENT BLOCK. The whole if chain is moot, unless you're at the third string. So again, store[], despite being an array of 10000 Strings, can only have one value in it, at most.

Once again, this might be why you're not finding much of anything in store[] - because you're NOT PUTTING ANYTHING THERE.

It's not some magic block on reading the variables. It's that you're writing a lot of code that doesn't do anything at all, and does it very badly.

No, I have corrected the array increment already. Now the z will be incremented, and hence every value will be stored.

Read the post. Read the code. Explain why you only assign into store if (amino==2). Then tell me how often that loop will write to the array.

I'll give you a hint: when you count, starting from zero, up to some number, how many times do you count 2?

amino==2 is actually my tokenizing part. I'm taking the second tokens of every row during file extraction.

No it's not. Here's what that section of your code boils down to:

amino =0;
while (true)
{
  amino ++;
  if (amino == 2)
  {
     System.out.println ("I just wrote to the array");

  }

}

How many lines of output will you see?

This question has already been answered. Start a new discussion instead.