Hi guys! I need help here, When ever I write onto my text file, i get null and then the value.Please help me! I don't want the "null"!

Here is how it looks like in Notepad++:

null1: 0.22056311934213296
2: 3.017771771149946

null3: 1.508399104807777
4: 0.07575171145562612

null5: 5.187081012091999
6: 2.049001095182013

null
null
null

Here are my codes:

count =0;
for(int a=0; a<countlength2; a++){
  for(int b=0; b<countlength1; b++){
  		
   R2=0.0;	
   
    R2 =(Math.pow((coordinatesRotZ[a][0]-coordinates1[b][0]),2)
        +Math.pow((coordinatesRotZ[a][1]-coordinates1[b][1]),2)
        +Math.pow((coordinatesRotZ[a][2]-coordinates1[b][2]),2));
                
    R1 += R2; //Store R1 for every loop into R2
    count++;
               
              
st[a] += Integer.toString(count)+": "+Double.toString(R2)+"\n"; //Change to String so as to store in .txt 
st_results[a] += Integer.toString(count)+": "+Double.toString(coordinatesRotZ[a][0])+"\t"+Double.toString(coordinatesRotZ[a][1])+"\t"+Double.toString(coordinatesRotZ[a][2])+"\t"+Double.toString(coordinates1[b][0])+"\t"+Double.toString(coordinates1[b][1])+"\t"+Double.toString(coordinates1[b][2])+"\t"+Double.toString(R2)+"\n";
      
System.out.println("Count: "+count);                 
System.out.println("Query:"+coordinatesRotZ[a][0]+"\t"+coordinatesRotZ[a][1]+"\t"+coordinatesRotZ[a][2]); 
System.out.println("Target:"+coordinates1[b][0]+"\t"+coordinates1[b][1]+"\t"+coordinates1[b][2]);   
System.out.println("RMSD:" +R2);             
//System.out.println("");


}
    }
    
 RMSD_Final =Math.sqrt(R1/count); //Sum of R1/numofcoordinates
 
  System.out.println("Final RMSD="+fmt.format(RMSD_Final));
    
    
//-----------------------Appending to File--------------------------------------

FileUtil util = new FileUtil();
util.writeLinesToFile("RMSDextractedCoordinates.txt", st, count, false);
util.writeLinesToFile("RMSDresults.txt", st_results, count, false);

Recommended Answers

All 16 Replies

If st[a] is the thing you are writing to the file, are you initializing it properly?

I know when you try to print out a null value it prints as "null", I'm just wondering if you do:

String s = null;  //or don't new it properly
s += "hello";
System.out.println(s);

you might get a null pointer exception, OR maybe "nullhello" try it and see, if it is the case you will need a st[a] = new String(); (which you should have anyway)

If st[a] is the thing you are writing to the file, are you initializing it properly?

I know when you try to print out a null value it prints as "null", I'm just wondering if you do:

String s = null;  //or don't new it properly
s += "hello";
System.out.println(s);

you might get a null pointer exception, OR maybe "nullhello" try it and see, if it is the case you will need a st[a] = new String(); (which you should have anyway)

Sorry, I don't really get what you mean here.Can you explain it to me again? Anw, I initialized it as:

private static String st[]= new String[20000];

String st[]= new String[20000];

this initializes (im not sure thats the right word) the array of strings, each element is still null!

take a look here http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

you still need, to set each item in the array to something, for example:

double[] array = new double[10] //makes an array of size 10 (each element is not been assigned)

array[0]=1;  //assign the first element
array[1]-2;  //assign the second element etc etc

you will need to call

st[a] = new String("what the string is going to start as");

for each element you are going to use

hope that helped

String st[]= new String[20000];

this initializes (im not sure thats the right word) the array of strings, each element is still null!

take a look here http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

you still need, to set each item in the array to something, for example:

double[] array = new double[10] //makes an array of size 10 (each element is not been assigned)

array[0]=1;  //assign the first element
array[1]-2;  //assign the second element etc etc

you will need to call

st[a] = new String("what the string is going to start as");

for each element you are going to use

hope that helped

Hmmmm, but I can't possibly assign for every element. Because my loop runs for over a thousand times. The above is just a small test file I'm working on. Do you think it's a problem with my write to file function, because if it's a single loop, it works fine without any null..

I don't know what you mean "can't possibly assign for every element" making a new string wont take as long as all the other stuff you are doing in the loop, have you even tried it? What you are saying just doesn't make any sense!

You "can't possibly" write your program properly?

If its a problem with your write to file function, not string initialization then try doing your strings properly (you can also see how much longer this takes, and whether its possible) if this resolves the problem then its not a problem with your write function - if not, then maybe. It doesn't seem hard to put in one line to test it (or see whether it is indeed impossible)

I don't know what you mean "can't possibly assign for every element" making a new string wont take as long as all the other stuff you are doing in the loop, have you even tried it? What you are saying just doesn't make any sense!

You "can't possibly" write your program properly?

I did, I tried. I don't really get it, please understand that my java knowledge is limited. i'm a beginner. I must assign each element in an array?

I did it this way:

st[a] += new String(Double.toString(R2));

I still get null

st[a] += new String(Double.toString(R2));

this adds a new string to the origional null string.

you need: st[a] = new String(); before you do any adding to it, for example at the beginning of your loop.

st[a] += new String("hi");

is the same as:

st[a] = st[a] + new String("hi");

is the same as

st[a] = st[a] + "hi";

(java makes a new string when you put "abc" cos its clever)
is the same as (for a null st[a])

st[a] = null + "hi";

and java prints "null" for a null object, so you are making new string, but you are assigning it to be "nullhi"

for your first time, just use = instead of +=

you dont actually have to use new to make a new string (i dont think), for example

String s = "a string";

is fine, Java interprets this as

String s = new String("a string");
st[a] += new String(Double.toString(R2));

Double.toString returns a String object, so you dont need to make a new String() at all... like i said, just make the first += an =

st[a] += new String(Double.toString(R2));

Double.toString returns a String object, so you dont need to make a new String() at all... like i said, just make the first += an =

I tried but I got the value for alternate loop:

3.017771771149946,
0.07575171145562612,
2.049001095182013,
null
null
null

count 1, 3, 5 is null.

Please post the new code after the changes.

Please post the new code after the changes.

count =0;
for(int a=0; a<countlength2; a++){
  R2=0.0;for(int b=0; b<countlength1; b++){
  		
   	
   
    R2 =(Math.pow((coordinatesRotZ[a][0]-coordinates1[b][0]),2)
        +Math.pow((coordinatesRotZ[a][1]-coordinates1[b][1]),2)
        +Math.pow((coordinatesRotZ[a][2]-coordinates1[b][2]),2));
                
    R1 += R2; //Store R1 for every loop into R2
    count++;
               
st[a] =(Double.toString(R2)+","); //Change to String so as to store in .txt 

//For reference     
System.out.println("Count: "+count);       
System.out.println("Query:"+coordinatesRotZ[a][0]+"\t"+coordinatesRotZ[a][1]+"\t"+coordinatesRotZ[a][2]); 
System.out.println("Target:"+coordinates1[b][0]+"\t"+coordinates1[b][1]+"\t"+coordinates1[b][2]);  
System.out.println(st[a]);    System.out.println(""); 

}
    }
    
 RMSD_Final =Math.sqrt(R1/count); //Sum of R1/numofcoordinates
 
//-----------------------Appending to File--------------------------------------

FileUtil util = new FileUtil();
util.writeLinesToFile("RMSDextractedCoordinates.txt",st, count, false);


 }//end of try

    catch( IOException e) {
	e.printStackTrace();
    }//end of catch

On line 11:

R1 += R2; //Store R1 for every loop into R2

You are doing exactly the opposite - you are storing The value of R2 into R1, fyi.
What is the expected output? are the numbers correct and it's just the nulls at the end or the numbers are not correct as well?

On line 11:

R1 += R2; //Store R1 for every loop into R2

You are doing exactly the opposite - you are storing The value of R2 into R1, fyi.
What is the expected output? are the numbers correct and it's just the nulls at the end or the numbers are not correct as well?

The values are right. I am exactly doing that. However when I write in my text file it skips count 1, 3 and 5 and gives me 2,4,6 instead:

3.017771771149946,
0.07575171145562612,
2.049001095182013,
null
null
null

My desired output is(count 1- 6):

0.22056311934213296
3.017771771149946
1.508399104807777
0.07575171145562612
5.187081012091999
2.049001095182013


The output in my command prompt is as such:

Count: 1
Query:-3.7819035300340316 15.1647454046431 13.227407098268056
Target:-4.04 15.048 13.602
Score: 0.22056311934213296,

Count: 2
Query:-3.7819035300340316 15.1647454046431 13.227407098268056
Target:-3.621 15.574 14.908
Score: 3.017771771149946,

Count: 3
Query:-3.619897092307956 15.566875473312168 14.63286414961019
Target:-4.04 15.048 13.602
Score: 1.508399104807777,

Count: 4
Query:-3.619897092307956 15.566875473312168 14.63286414961019
Target:-3.621 15.574 14.908
Score: 0.07575171145562612,

Count: 5
Query:-2.809864903677579 14.524319306095832 15.44580237219716
Target:-4.04 15.048 13.602
Score: 5.187081012091999,

Count: 6
Query:-2.809864903677579 14.524319306095832 15.44580237219716
Target:-3.621 15.574 14.908
Score: 2.049001095182013,

Post the entire code please.

Post the entire code please.

package genesis;

import java.io.*;
import java.util.*;
import java.text.*;

//------------------------------------------------------------------------------
class GetFilenameWithoutExtension{

public static String getFileNameWithoutExtension() {
  String fileName="RMSD"; //manual input of file name //GUI
  File file = new File(fileName);

  int index = file.getName().indexOf('.'); // edited from lastIndexOf()
      if (index>0&& index <= file.getName().length() )//took out -2
      {
      System.out.println(" The coordinate values of Protein ID: "+file.getName().substring(0, index)+ " has been extracted.");

      }
	  return fileName;
    }
}
class FileUtil {

  public void writeLinesToFile(String filename,
              String[] linesToWrite,int length,
              boolean appendToFile) {

   PrintWriter pw = null;

    try {

      if (appendToFile) {

        //If the file already exists, start writing at the end of it.
        pw = new PrintWriter(new FileWriter(filename, true));

      }
      else {
        pw = new PrintWriter(new FileWriter(filename));
        //this is equal to:
        //pw = new PrintWriter(new FileWriter(filename, false));

      }

      for (int i = 0; i <length; i++) {

        pw.println(linesToWrite[i]);

      }
      pw.flush();

    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      //Close the PrintWriter
      if (pw != null)
        pw.close();

    	}

  	}
  }


//------------------------------------------------------------------------------
// class WriteFile - to append file name to text file


class WriteFile {

	private String path;
	private boolean append_to_file = false;

	public WriteFile(String file_path)
	{
		path = file_path;
	}

	public WriteFile (String file_path, boolean append_value)
	{
		path = file_path;
		append_to_file = append_value;
	}

	public void writeToFile (String textLine) throws IOException
	{
		FileWriter write = new FileWriter(path, append_to_file);
		PrintWriter print_line = new PrintWriter(write);

		print_line.printf( "%s" + "%n", textLine);
		print_line.close();
	}
}//end of class WriteFile


//------------------------------------------------------------------------------

public class testest4{

   private static StringBuffer buffer;
   private static BufferedReader input1=null;
   private static String st[]= new String[20000]; //keep at 20000, initially 1000
   private static String st_results[]= new String[20000];
   private static String RMSD[]= new String[20000];

   public static String [] arrayM1 = new String [3000];  
   public static String [] arrayM2 = new String [3000];
   public static double [] arrayno1 = new double [2000];
   public static double [] arrayno2 = new double [2000];
   public static double [][] coordinates1 = new double [10000][100];
   public static double [][] coordinates2 = new double [10000][100];
   public static double [][] coordinates2T = new double [10000][100];
  
   

   public static double [][] coordinatesRotz = new double [10000][100];
   public static double [][] coordinatesRotX = new double [10000][100];
   public static double [][] coordinatesRotZ = new double [10000][100];

   static DecimalFormat fmt= new DecimalFormat("0.000"); //3 D.P

   public static void main(String args[]) {


   int i=0,j=0;
   String text1;
   String text2;
   double X=0.0;
   double Y=0.0;
   double Z=0.0;
   double RMSD_Final = 0.0;
  
   int counter2=0;
   String line2="";
   int counter1=0;
   String line1="";
   double R1 = 0.0;
   double R2 = 0.0;
   int count =0;
   int countlength1=0;
   int countlength2=0;
   
   try{
   	


        FileInputStream fstream1 = new FileInputStream("C:\\Users\\Hazel\\Documents\\Desktop\\MPSIP\\proteintest1.txt");// Target
        FileInputStream fstream2 = new FileInputStream("C:\\Users\\Hazel\\Documents\\Desktop\\MPSIP\\proteintest2.txt");// Query
        DataInputStream in1 = new DataInputStream(fstream1); // Get the object of DataInputStream
        DataInputStream in2 = new DataInputStream(fstream2); // Get the object of DataInputStream
        BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
        BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
    
        countlength1=0;//text1 count
        
        while ((text1 = br1.readLine()) != null)   {  //Read File Line By Line

            if(text1.trim().startsWith("ATOM")) {
        	StringTokenizer s1 = new StringTokenizer(text1," ");
            countlength1++;
            
          	while(s1.hasMoreTokens()) {

			String ss1 = s1.nextToken();
		    	counter1++;

		    	if(counter1 == 3){
		    		line1 += ss1;
		    		arrayM1[i] = ss1;
		    		
		    		
		    		}
		    			
		    		
		    	}
	
                coordinates1[i][0]= Double.parseDouble(text1.substring(30,38));//X
                coordinates1[i][1]= Double.parseDouble(text1.substring(38,46));//Y
                coordinates1[i][2]= Double.parseDouble(text1.substring(46,56));//Z
                
		i+=1;		
		
            }//end of if
                
	} //end of while.

	i=0;
	
    countlength2=0;//text2 count
    
	while ((text2 = br2.readLine()) != null)   {  //Read File Line By Line

            if(text2.trim().startsWith("ATOM")) {
        	StringTokenizer s2 = new StringTokenizer(text2," ");
        	countlength2++;
        	while(s2.hasMoreTokens()) {

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

		    	if(counter2 == 3){
		    		line2 += ss2;
		    		arrayM2[i] = ss2;
		    	}
		}

                coordinates2[i][0]= Double.parseDouble(text2.substring(30,38));//X
                coordinates2[i][1]= Double.parseDouble(text2.substring(38,46));//Y
                coordinates2[i][2]= Double.parseDouble(text2.substring(46,56));//Z
                
                
                
                i+=1;
                

            }//end of if

	} //end of while.


//------------------------------Translation-------------------------------------


    for(int a=0; a<countlength2; a++) {
    	
        for(int b=0; b<3; b++){
            for(int c=0; c<3; c++){

                X = coordinates1[1][0]/coordinates2[1][0]; //alpha c coordinate
                Y = coordinates1[1][1]/coordinates2[1][1];
                Z = coordinates1[1][2]/coordinates2[1][2];

                double [][] Translation1={ {X,0.0,0.0}, {0.0,Y,0.0}, {0.0,0.0,Z} };

                coordinates2T[a][b] += coordinates2[a][c]*Translation1[c][b];
        
        
       

//-------------------------Rotation & RMSD Cal----------------------------------

//Uses Leohard Euler's angle of rotation theorem
//1 degree in rad.

double degrees=0.087266463/5;

                double [][] Rotz={ {Math.cos(degrees), Math.sin(-degrees), 0.0},
                     {Math.sin(degrees), Math.cos(degrees), 0.0},
                    {0.0, 0.0 , 1.0} };

                double [][] RotX={ {1.0,0.0,0.0},
                    {0.0,Math.cos(degrees), Math.sin(-degrees)},
                    {0.0,Math.sin(degrees), Math.cos(degrees)} };

                double [][] RotZ={ {Math.cos(degrees), Math.sin(degrees), 0.0},
                    {Math.sin(-degrees), Math.cos(degrees), 0.0},
                    {0.0, 0.0 , 1.0} };

                coordinatesRotz[a][b]+= coordinates2T[a][c]*Rotz[c][b];
                coordinatesRotX[a][b]+= coordinatesRotz[a][c]*RotX[c][b];
               coordinatesRotZ[a][b]+=coordinatesRotX[a][c]*RotZ[c][b];
              
             

            }
        }
    }

 count =0;
for(int a=0; a<countlength2; a++){
  	R2=0.0;	
  for(int b=0; b<countlength1; b++){
  
   	
   
    R2 = (Math.pow((coordinatesRotZ[a][0]-coordinates1[b][0]),2)
        +Math.pow((coordinatesRotZ[a][1]-coordinates1[b][1]),2)
        +Math.pow((coordinatesRotZ[a][2]-coordinates1[b][2]),2));
                
    R1 += R2; //Store R1 for every loop into R2
    count++;
          
st[a] =(Double.toString(R2)+","); //Change to String so as to store in .txt 

//st_results[a] += Integer.toString(count)+": "+Double.toString(coordinatesRotZ[a][0])+"\t"+Double.toString(coordinatesRotZ[a][1])+"\t"+Double.toString(coordinatesRotZ[a][2])+"\t"+Double.toString(coordinates1[b][0])+"\t"+Double.toString(coordinates1[b][1])+"\t"+Double.toString(coordinates1[b][2])+"\t"+Double.toString(R2)+"\n";
 


     
System.out.println("Count: "+count);       
System.out.println("Query:"+fmt.format(coordinatesRotZ[a][0])+"\t"+fmt.format(coordinatesRotZ[a][1])+"\t"+fmt.format(coordinatesRotZ[a][2])); 
System.out.println("Target:"+coordinates1[b][0]+"\t"+coordinates1[b][1]+"\t"+coordinates1[b][2]);  
System.out.println("Score: "+st[a]);    
System.out.println(""); 



}
    }
    
 RMSD_Final =Math.sqrt(R1/count); //Sum of R1/numofcoordinates
 

//RMSD[a] = Double.toString(RMSD_Final);

System.out.println("Final RMSD="+fmt.format(RMSD_Final));


//-----------------------Appending to File--------------------------------------

FileUtil util = new FileUtil();
util.writeLinesToFile("RMSDextractedCoordinates.txt",st, count, false);

//util.writeLinesToFile("RMSDresults.txt", st_results, count, false);
//util.writeLinesToFile("RMSDresults.txt", RMSD,1, false);


 }//end of try

    catch( IOException e) {
	e.printStackTrace();
    }//end of catch



}// end of main
}
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.