Hi. I have a 2D array in a particular class file. Now, I want to equate a 2D array from another class to it. May I know how to do it? So far, this is what I've done:

Example:

private double[][] residuescores = MatchApplet.mydouble;

residuescores is from a class itself, and mydouble is from the class MatchApplet. However, I realised by equating it like that, the 2D array, mydouble, is actually empty or has got error. May I know how to equate it properly? Do I do it like this?

private double[][] residuescores = MatchApplet.mydouble[a][b];

If I do it the second way, there's error saying the a and b is not declared. However, I've declared it in MatchApplet already. I need help here. Thank you!

Recommended Answers

All 24 Replies

In your MatchApplet class, create a public method called get2DArray, or getMyDouble, or getResidueScores - something that makes sense in your program. The method should be of type double[][], and should return the variable called mydouble. If mydouble is a static array, then the method can be static too. If mydouble is not static, then the class where residuescores is defined will need a reference to a MatchApplet object in order to call the method.

In the class where residuescores is defined, you can do the assignment in one of 2 ways. If mydouble is static, then the assignment will look like this:

private double[][] residuescores = MatchApplet.getMyDouble();  // or whatever you called the method

If mydouble is not static, then the assignment will look like this:

private double[][] residuescores = matchAppletInstance.getMyDouble();  // or whatever you called the method

In the second case, matchAppletInstance is an object instance of the MatchApplet class.

Okay thanks I got what you meant. However, when I create the method, my method is:

abstract double[][] getMyDouble();

But later on when I used this method to return mydouble, it has error saying "cannot return a value from method whose type is void".

This was how I return:

abstract double[][] getMyDouble()
{ return mydouble[a][b]; }

Is there any mistake?

Take out the keyword abstract. Make it public instead.

It's the same if I put public. At te declaration of the method there, there will be this error: missing method body, or declare abstract.

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

class MatchApplet extends JApplet {


	TextArea outputArea;
	JButton button;
	JButton reset;

	JTextField tF1;
	JTextField tF2;

	JLabel l1;
	JLabel l2;

	String s1;
	String s2;

        static String display1 = "";
  	static String display2 = "";
        static String display = "";
        static double mydisplay;

        static double[][] mydouble = new double [1000][1000];
        int a, b;

        String[] temp;
        static double d;
        
        abstract public double[][] getMyDouble();
        
        

	public static void main(String[] args) throws Exception
	{
            //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

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



  	public void init()
	{

		try
		{
                BufferedReader in1 = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\1a00(50).txt"));	//reading files in specified directory
                BufferedReader in2 = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\1a0a(50).txt"));	//reading files in specified directory
                BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory
                

  			String str1;
			while ((str1 = in1.readLine()) != null)	//file reading
			{
                            display1 = str1;
                            System.out.print(display1);
  			}
  			in1.close();

  			System.out.println("");

			String str2;
			while ((str2 = in2.readLine()) != null)	//file reading
			{
                            display2 = str2;
                            System.out.print(display2);
  			}
			in2.close();

                        

                        String str;
                        while ((str = in.readLine()) != null)	//file reading
                        {

                            temp = str.split(",");

                            for (String s : temp)
                            {
                                d = Double.parseDouble(s);
                                mydouble[a][b] = d;
                                System.out.println(mydouble[a][b]);
                            
                            }
                            
                            double[][] getMyDouble()
                            { return mydouble[a][b]; }
                            
                        
                            
                        }
                        in.close();

        
       

		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);

		tF1 = new JTextField(display1);
		tF2 = new JTextField(display2);

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

		c.add(l1);
		c.add(tF1);
		c.add(l2);
		c.add(tF2);
		c.add(outputArea);


	final Substitution sub = new Blosum50();

		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");


      }catch( IOException ioException ) {}


  }//end of init()

}//end of class




// The class of substitution (scoring) matrices

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

  void buildscore(String residues, String residues2, double[][] residuescores)
  {
    // Allow lowercase and uppercase residues (ASCII code <= 127):
    score = new double[127][127];
    for (int i=0; i<residues.length(); i++)
    {
      char res1 = residues.charAt(i);
      for (int j=0; j<=i; j++)
      {
        char res2 = residues2.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();
  abstract public String getResidues2();
}


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

class Blosum50 extends Substitution
{

  private String residues = MatchApplet.display1;
  private String residues2 = MatchApplet.display2;

  public String getResidues()
  { return residues; }

  public String getResidues2()
  { return residues2; }

  private double[][] residuescores = MatchApplet.getMyDouble();
            

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

This is my codes. The affected parts are lines 32, 105, 106, 211.

1. Get rid of line 32.
2. On lines 105-106 you are defining a new method. You cannot do this inside another method. Move these 2 lines so they come after 161 and before 163. Also, put keyword static in front of method declaration. (static double[][] getMyDouble...)
3. Line 211 should be ok after making these changes.

Hi thanks. I did that, but I think there seems to be some problem with the array itself. It says "required: double[][], but found double". I did return mydouble[a], but I don't know why there is still this error.

Oh, I didn't notice that before. When you return mydouble[a], that refers to the value stored at row a, column b of your 2d array. The value stored there is just a double. But you actually want to return the whole array mydouble, not just one value. So take away the indices.

return mydouble;

Hi. It finally has no error now, after I just return mydouble. However, if I just print my 2D array mydouble itself, it doesn't print it out. It should be numbers coming out, but instead, I'm getting this:

[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22
[[D@1af9e22

I need to print mydouble[a] then what I want is printed out. If I just print mydouble, the above comes out. May I know what can I do so that I just need to print mydouble itself and the result would just come out, instead of mydouble[a]?

I'm not sure I understand what you're asking, but the usual way to print a 2d array is with 2 nested for loops like this:

for (int i = 0; i < ROWS; i++)
      for (int j = 0; j < COLS; j++)
         System.out.println(mydouble[i][j]);

where ROWS is the first dimension and COLS is the 2nd dimension of the 2d array.

Yes I'm looking for something like this. Thank you so much, I will try it out.

Hi, may I know what is my ROWS and COLS here in this case? Because I can't just declare ROWS and COLS, it is empty.

How do I equate rows and cols for my text file? Because I've already split it, then parse it, so now the numbers in my text file are all individuals.

ROWS and COLS refer to your 2D array. If you know in advance how much data you're going to read in, then you already know the size of your array. If you don't know in advance, then you should count the rows and columns as you read in the data from the file.

How do I count the rows and columns of data as I read?

I don't know much about the data you are reading, but presumably you do. Is the data somehow 2 dimensional? When you store it in your 2d array, how do you know when to change the row index vs. the column index?

Can you describe the data you are reading from the file? Does it have some kind of structure?

Yes it does. In the text file, there are only numbers (decimal numbers), both positive and negative, and are separated by comas. There are 30 rows and 30 columns.

Then you can declare the variables like this:

private static final int ROWS=30, COLS=30;

This discussion about the array size seems to have gone off in a strange direction.
Regardless of where you get the array from you can find out its length at runtime using the "length" attribute that every array has.
The following code illustrates this

for (int i = 0; i < mydouble.length; i++)
  for (int j = 0; j < mydouble[i].length; j++)
    System.out.println(mydouble[i][j]);
  }
}

Note the second line - Java 2d arrays don't have to be rectangular, so it's not always correct to use a simple ROWS/COLS size. This form of the code copes with that.

I think the array has a fixed size, something like 1000x1000 elements, but that's not the size of the data. So querying the array for its size isn't the appropriate answer in this case.

Hi all thanks for the help. However, the size the my 2D array depends on the text file I'm going to read. In this case, instead of mydouble.length, I should use something else no? Because mydouble is just the array itself, not the number of rows and columns in my text file?

OK, yes. I assumed the array had been sized to fit the data.My mistake.
(That's why people use ArrayLists and Vectors!)
Sorry. J

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.