hi. could some one help me. I am trying to read the tokens into the array but the datatypes are incompatible. what should i do to cast it into the same thing. the numbers from my text file are actually floats. But i can make do with just the integers if it aint possible.

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

public class BasisGenesis {

//variables
//Mu (the model structures)

    public static void main(String[] args)                                                                                                                          //main method

 {

File dir = new File("1a00.gz.txt"); 					                                                                          //set file
     String path = dir.getAbsolutePath();																																	         //get file path
     int lala = path.lastIndexOf("\\");																																		//get index of '\'
     String howPath = path.substring(0,lala+1);																														                        //extract directory name
     File usePath = new File(howPath);																																			 //assign directory for reading file
     String[] fileDir = usePath.list();																																					   //store file in dit to array
     if(fileDir == null) 							                                     																									//check if dir exists
     {
     	System.out.println("Directory Does Not Exist");
     }
      else
      {
     	for(int j=0; j<fileDir.length;j++)

     	{
     	   String fileName = fileDir[j];


int count = 0;


try
 {

BufferedReader in = new BufferedReader(new FileReader(fileDir[j]));			

String str;


while ((str = in.readLine())!=null)  									
{

StringTokenizer s = new StringTokenizer(str," ");                 
int counter=0;   //every line has 2 tokens
String line="";



				//2D intialising
				int row = 0;
				int col = 0;
				int [][] array = null;


				while(s.hasMoreTokens())
				{

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

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//read into 2D array

				if (counter==1)

				{
			   row = Integer.parseInt(ss);//take the first line and put into the row:

			}

			 else if (counter == 2)
			 {
			 //take the second line and put it into the col:

              col = Integer.parseInt(ss);

			   array = new int[row][col];
			   }

}//end of while
 System.out.println(line); 
 line +="\0";


}//end of while
              													                            
              in.close();														    
}//end of try
catch (IOException e) { }

}//end of for
}//end of else
}//end of main method

thanks much!!!!

Recommended Answers

All 16 Replies

the datatypes are incompatible

Do you get errors? Please copy and paste the full text of the messages here.

Build process is complete. but it cannot run. the error msg is this:

Exception in thread "main" java.lang.NumberFormatException: for input String "0.0 0.0"
at java.lang.Interger.parseInt(Integer.java:458)
java.lang.Interger.parseInt(Integer.java:499)
at BasisGenesis.main(BasisGenesis.java:80)

because the first 9 lines of my text file is

0.0 0.0
0.0 0.0
101.601 38.534
103.062 38.513
103.354 38.323
103.025 37.252
103.8 37.438
105.274 37.822
103.166 37.064

i have tried to use Float.parseFloat but it didnt work. and i guessed it is because it has been orginally part of a string. appreciate if you could advise me. thanks again.

The runtime error thrown is pretty clear here; you are trying to parse the string "0.0 0.0" as an integer which won't work for obvious reasons and hencefails. Here is something you should attempt, one step at a time:

  • Read a single line from a file, print that line and verify if the lines are being read properly
  • Split the line on a whitespace character; a space in your case
  • Print out both the tokens and verify their value; both tokens should be valid "float" strings i.e. of the format X.Y

Tackle the problem in steps; first try out the parsing part for a hardcoded string. E.g.

String str = "0.0 0.0";
String[] splits = str.split("\\s");
// parse the first part as float; do the same with the second part
// print out the results and verify it

I'm stuck at here.. there is still a loss of precision.. due to the datatype casting. are there any essential declarations that I am missing out. Should i throw a number format exception? is that it? or should i use valueOf() for the casting?

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

public class BG {

    public static void main(String[] args)
    {
        File dir = new File("1a00.gx.txt");

        String path = dir.getAbsolutePath();
        int root = path.lastIndexOf("\\");
        String continuePath = path.substring(0, root+1);
        File usePath = new File(continuePath);

        String[] fileDir = usePath.list();

        if (fileDir == null) {
            System.out.println("Directory Does Not Exist");
        } else {
            for (String file : fileDir) {
                parseFile(file);
            }
        }
    }

    private static void parseFile(String fileName) {
        try {
            BufferedReader in = new BufferedReader(new FileReader(fileName)); //reading files in specified directory
            String str;

            while ((str = in.readLine()) != null) {//file reading
                parseString(str);
            }
            in.close();
        }
        catch (IOException e) {
            // At least log it or output something
        }
    }

    private static void parseString(String str) {
        String[] parts = str.split(" ");
        if(parts.length>=2) {
            double row = Double.parseDouble(parts[0]); //causes a loss of precision
            double col = Double.parseDouble(parts[1]);
            double[][] array = new double[row][col]; // I'm going to do something with the array
        }
    }

}//end of Basis Generation

The code snippet works out well for me. For which set of data are you getting the loss of precision error? Why would storing a double inside a double variable cause precision loss? The only problem I see is your using double as an array index, which you can't. Why would you want to use a parsed double as an index to your array. I'm not sure what you are trying to achieve here...

I'm getting a loss of precision at the initialisation of the array.

ok. chop chop. I saw yr profile. Are you familiar with Geometric Hashing?

I am trying to get the coordinate values into a 2D array before I set the the first set of elements as the index into the hash table. And to answer why i have to pass double its cause the coordinates of my proteins are in double datatypes. as i have mentioned and shown a sample of the text file in a reply above.

Am I on the right track or should I change my approach to implementing the algorithm?

okies. I got the datatype casting thing solved. Someone reccommended an explicit downcast. It's running fine now. But I hope to print out the 2D array to see the elements coming through. You think you can help me identify the problem? I can't find it.. Thanks A LOT!!

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

public class BasisGenesis {

public static void main(String[] args)                                                                                                                                       
 {
	  File dir = new File("1a00.gz.txt"); 
     String path = dir.getAbsolutePath();
     int root = path.lastIndexOf("\\");
     String howPath = path.substring(0,root+1);
     File usePath = new File(howPath);
     String[] fileDir = usePath.list();
     if(fileDir == null)
     {
     	System.out.println("Directory Does Not Exist");
     }
      else
      {
     	for(int j=0; j<fileDir.length;j++)
     	{
     	   String fileName = fileDir[j];
     	try
      {

     	    BufferedReader in = new BufferedReader(new FileReader(fileDir[j]));  
            String str;

      		 while ((str = in.readLine()) != null) 
      		 {
               String [] parts = str.split(" "); 
             if (parts.length>=2)
             	{
               	double row = Double.parseDouble(parts[0]);
               	double col = Double.parseDouble(parts[1]);
               	//explicit downcast
               	double [][] array = new double [(int)row] [(int)col];
                System.out.println(array); //here's the problem. I can't seem to print out the array.

/* Should I be using something like this instead.
                for (int r=0; r< array.length; r++) {
                for (int c=0; c<array[r].length; c++) {
                      System.out.print(" " + array[r][c]);
                        }
                      System.out.println("");
                }
*/ 
                  }

              }//end of while
              in.close();
              System.out.println("Coordinates are now in a 2-Dimensional array.");
              }//end of try
           catch (IOException e) {
           	System.out.println("Failed to process string. Please try again."); }
     	}//end of for
      }//end of else
	}//end of main method

help me identify the problem

Can you show the current output and the output you want?
Of if the problem is something else, please explain.

I want the output to depict the 2D array being printed out for each file, LINE 38. But it doesnt print the array.

The current output is "Coordinates are now in a 2-Dimensional array." appearing for every file i'm processing.. and that is 11,475 times.

I want the output to depict the 2D array being printed out for each file, LINE 38. But it doesnt print the array.

The current output is "Coordinates are now in a 2-Dimensional array." appearing for every file i'm processing.. and that is 11,475 times.

Ok. I don't really know what information i need to give you before you'd understand. But I think this would help,

you see, my text file contains the coordinates this way

"0.0 0.0
0.0 0.0
101.601 38.534
103.062 38.513
103.354 38.323
103.025 37.252
103.8 37.438
105.274 37.822
103.166 37.064
...."

thereafter, i downcast it from Strings to int then to doubles in 2D array.

What i hope to acheive is something like this:

element 1 [[0.0][0.0]]
element 2 [[101.062][38.534]]
element 3 [[103.354][38.323]]
....


Please tell me whether this is correct. I think I should define 2 columns only in the 2D array initialisation and oppose to the arrays of arrays that i am getting now.. How should I do it?

To get your desired output try this:
System.out.println("element" + row + "[[" + array[row][0] + "][" + array[row][1] + "]]");

This assumes there are two elements on each row.

A downcast is not what you need. Why? Because:

int i = (int)123.123; // 123
i = (int)123.223; // 123
i = (int)123.999; // 123

See the problem?

> double [][] array = new double [(int)row] [(int)col];

This will effectively declare a `double` array of dimensions `row x col` for *each* line read and then effectively discard it. You never save the actual value which you read.

All in all, the approach is flawed on many levels; what is required here is for you to jot down a plain text algorithm and trasnlate it to Java rather than diving head first into code. Reading the introductory Java language tutorials might help the cause here.

Begin with:
- Read a line from the text file and split the contents into a double pair
- Create a new Point class object for the double pair which will hold the x & y coordinates for a given point
- Add the newly created object to a List
- and so on....

You need to write down the "actual" problem statement here rather than what you make of the problem statement. That might help the members here in helping you better.

Hey guys. I think, and as some of you have advised, this will cause me less trouble. - using an ArrayList. I wanted to use the 2D array approach so that the the coordinates themselves can be variables. But I realised that I can just have each pair as a variable. It's done! Thank you thank you thank you SOOO much. I have learnt soo much from you! I'm sorry for understating my queries. Sorry, I'm growing out of it. :P I will be further processing the coordinates later on. It's Geometric Hashing that I am doing.

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

public class BasisGenesis {

public static void main(String[] args)                                                                                                                               
 {
     File dir = new File("1a00.gz.txt");
     String path = dir.getAbsolutePath();
     int root = path.lastIndexOf("\\");
     String howPath = path.substring(0,root+1);
     File usePath = new File(howPath);
     String[] fileDir = usePath.list();
     if(fileDir == null)
     {
     	System.out.println("Directory Does Not Exist");
     }
      else
      {
     	for(int j=0; j<fileDir.length;j++)
     	{
     	   String fileName = fileDir[j];
     	try
      {
     	    BufferedReader in = new BufferedReader(new FileReader(fileDir[j]));  
            String str;
            ArrayList<String> arrayList = new ArrayList<String>();

            while ((str = in.readLine()) != null)
              {
               arrayList.add(str) ;
               System.out.println( fileName + arrayList);
              }//end of while
              in.close();
           System.out.println("Coordinates of each Protein in the database are now in an arraylist.");
              }//end of try
           catch (IOException e) 
          {System.out.println("Failed to process file. Please try again."); }

          }//end of for
     	}//end of else
      }//main method
    }//class

You are of course welcome; good luck with your project. :-)

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.