Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default combining two separate codes into one

    I have two programs, one which reads data from .csv file and other which performs certain calculations based on the data entered by the user through keyboard.

    Code for reading data from .csv file :-
    //class to read CSV file :

    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.*;


    public class readCSV1

    { //readCSV class starts here

    public static void main(String args[]) throws IOException

    { //main method starts

    String fName = "test1.csv";//csv file which u wanna read

    String thisLine; //string variable to take each record at a time

    int count=0;


    FileInputStream fis = new FileInputStream(fName);
    //A FileInputStream obtains input from a file

    DataInputStream myInput = new DataInputStream(fis);
    /*data input stream lets an application read primitive Java data types
    from an underlying input stream*/

    while ((thisLine = myInput.readLine()) != null)
    { //beginning of outer while loop
    String[] result = thisLine.split(",");
    for (int x=0; x<result.length; x++)
    { System.out.println(result[x]);

    }
    System.out.println();

    }
    }
    }

    Code for accepting data from keyboard entries and output the results based on certain calculations:

    import java.io.*;

    public class calculations {


    public static void main (String[] args) throws IOException

    {
    double rootingdepth=0.6;
    double asws=125;
    double sws;
    double allowablecoefficient=0.45;
    double mad;


    double kc=0.42;

    double[] netsoilwaterbalance;
    double[] waterreqdforirrigation;
    double initialsoilwaterbalance;

    int i=0;
    int a=0;




    System.out.println ("Enter the days of available data");
    int n=MyInput.readInt();



    double[] rainfall = new double[n];
    double[] eto = new double[n];
    double[] etc = new double[n];

    netsoilwaterbalance = new double[n];
    waterreqdforirrigation = new double [n];

    sws = rootingdepth*asws;
    mad = sws*allowablecoefficient;

    initialsoilwaterbalance = mad;


    for (i=0;i<n;i++)
    { a=i+1;
    System.out.println("Enter the rainfall values for" + a + "days");
    rainfall[i] = MyInput.readDouble();



    System.out.println("Enter the ETo values for" + a + "days");
    eto[i] = MyInput.readDouble();



    etc[i] = kc*eto[i];
    }



    for (i=0;i<n;i++)
    {
    a=i+1;

    netsoilwaterbalance[i] = initialsoilwaterbalance + rainfall[i] - etc[i];
    System.out.println ("the amount of water in the soil on day" + a + "is" + netsoilwaterbalance[i]);
    initialsoilwaterbalance = netsoilwaterbalance[i];

    if (netsoilwaterbalance[i] <= mad)
    { System.out.println ("Irrigation is required on day" + a);

    waterreqdforirrigation[i] = mad - netsoilwaterbalance[i];

    System.out.println ("water reqd for irrigation on day" + a + "is" + waterreqdforirrigation[i]);
    }
    else
    { System.out.println ("Irrigation is not required on day" +a);
    }

    }

    }

    }

    Now, my requirement is to eliminate the task of getting data from the user (from keyboard) and replace it with reading the same data from .csv file. (Both the rainfall and ETo values are stored in a particular .csv file).
    So, pls guide me on how to use both the above codes for satisfying my requirement.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You are trying to combine two non-OOP "classes" and it is very difficult if impossible to do. It suggest that you are getting way ahead of yourself. Why not back up a bit, and either read a book on Java programming with an emphasis on object-oriented programming, or go through the very basic portions of the Sun tutorials before you try to do any "combining" here.

  3. #3
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    You are trying to combine two non-OOP "classes" and it is very difficult if impossible to do. It suggest that you are getting way ahead of yourself. Why not back up a bit, and either read a book on Java programming with an emphasis on object-oriented programming, or go through the very basic portions of the Sun tutorials before you try to do any "combining" here.
    thnx for providing me with such wonderful suggestion !!!...i wont some technical reply dude..

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Dude: You've got two classes each with nothing but a main method, and that just won't do. The answer is: learn Java so you can create classes that don't have everything static. Sorry, but you have to learn to crawl before you can walk. You may not like this answer or this fact, but that won't alter its being true.

    Have you created true OOP classes yet, classes with non-static methods, with constructors, and all? To solve this, you'll need to know how to do this, and the best place to find out is the tutorials or a decent book. Best of luck.

  5. #5
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default uuuhhh... how rude

    That's not very nice way to reply to somebody that is giving you some very good advice.

    Now let's see ... I'm assuming that you programmed both pieces of code and I'm also assuming that you know what the two pieces code are doing. Based on the previous assumptions, write down on a piece of paper what the flow of the code should be and then relate it the pieces of code you already have and put the Frankenstein code together. When you finish you will have what is known as "Spaghetti" code. Why do I say this ? You are not using methods, constructors, etc that would make the code more efficient and understandable.

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  6. #6
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    thnx...well i am thinking to write a single class which would read the file, its contents, assign variables to those variables ..
    and the main method will perform the calculations.

    so, i am now thinking on how to use methods n constructors in that single class..

    is it a correct way m thinkin ??

  7. #7
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default On your way...

    Break your code into logical methods... one for the file handling, other methods for the different types fo calculetions (eto, etc, mad, etc)... what ever makes sense, maybe another method for printing results, etc.
    Your main method should really only be handling the calling of the methods.
    Also... do your coding in bite size chunks. First work on the method for opening the file. Once that's working, go for the method that reads the file contents. Once that is working, go for one of the calculation methods, etc.

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  8. #8
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    well i hav tried to build following code with 3 different methods:
    first method reads the data from file and outputs it
    second method returns the double by converting the string into double
    third method makes these values (all of them) to zero.

    //code
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.*;


    public class finalcode2

    { //readCSV class starts here

    public static void main (String[] args) throws IOException
    { fileread();
    double orig_values[] = parseDouble(result[x]);
    system.out.println ("original values" +orig_values[x]);
    zero (orig_values);
    }

    public static void fileread() throws IOException
    {

    String fName = "data.csv";//csv file which u wanna read

    String thisLine; //string variable to take each record at a time

    int count=0;
    int x=0;



    FileInputStream fis = new FileInputStream(fName);
    //A FileInputStream obtains input from a file

    DataInputStream myInput = new DataInputStream(fis);
    /*data input stream lets an application read primitive Java data types
    from an underlying input stream*/

    while ((thisLine = myInput.readLine()) != null)
    { //beginning of outer while loop

    String[] result = thisLine.split(",");
    for (x=0; x<result.length; x++)
    {

    System.out.println(result[x]);
    }


    }
    }



    public static double parseDouble(String array[])
    { return double numbers[] = array[];
    }



    public static void zero (double numtozero[])
    { int y=0;
    double allzero[] = new double[y];
    for (y=0; y<numtozero.length;y++)
    {
    allzero[y] = numtozero[y] * 0;
    System.out.println ("all zeroes" + allzero[y]);
    }

    }
    } //code

    but it shows following errors:-
    C:\Users\Jaimin\Documents\JCreator Pro\MyProjects\finalcode2.java:65: '.class' expected
    { return double numbers[] = array[];
    ^
    C:\Users\Jaimin\Documents\JCreator Pro\MyProjects\finalcode2.java:65: illegal start of expression
    { return double numbers[] = array[];
    ^
    C:\Users\Jaimin\Documents\JCreator Pro\MyProjects\finalcode2.java:65: ';' expected
    { return double numbers[] = array[];
    ^
    C:\Users\Jaimin\Documents\JCreator Pro\MyProjects\finalcode2.java:65: illegal start of expression
    { return double numbers[] = array[];
    ^
    4 errors

  9. #9
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default

    Java Code:
    public static double parseDouble(String array[])
    { [B][COLOR="Red"]return double numbers[] = array[];[/COLOR][/B]
    }
    The above return statement is very wrong (all by itself it produces 4 compile erros !!!). The parseDouble method receives a string array and returns a double. The statement "double numbers[] = array[] does nothing.
    Please explain what this method is suposed to do:
    • Turn an array element into a double ? or
    • Convert the whole array of strings into an array of doubles?

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  10. #10
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    this method converts every array element into double.

    i want to convert every value stored in the string to double coz i want to perform certain calculations on those numbers read from the file. and if i keep those as strings, i wouldn't be able to perform any operations. so, wants to convert all of them into double

  11. #11
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default

    OK... well, that is not the way to do it. You have to do the following steps in your method:
    • Create the "numbers" array (same length of the array that was passed to the method)
    • in a loop, convert each array element to a double and the assign it to the "numbers" array.
    • Retun the "numbers" array


    Java Code:
    public static double [] strArray2DblArray(String [] strArray)
    {
      double [] dblArray = new double[strArray.length]; //create double Array with same sizas as tha string array
      for (int i = 0; i<strArray.length;i++)
         {
          dblArray[i] = Double.parseDouble(strArray[i]);
         }
     return dblArray;
    }
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  12. #12
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    Java Code:
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.*;
    
    
    public class finalcode2 
    
    {  
    
    public static void main (String[] args) throws IOException   
    {  
        
         String[] output = fileread("data2.csv");
        double orig_values[] = strArray2DblArray (output);
      
         zero (orig_values); 
          }
    
    
       public static String[] fileread(String fName) throws IOException  
    {
    
    String thisLine; //string variable to take each record at a time
    
    int count=0; 
    int x=0;
    
    
    
    FileInputStream fis = new FileInputStream(fName); 
    //A FileInputStream obtains input from a file 
    
    DataInputStream myInput = new DataInputStream(fis);
    /*data input stream lets an application read primitive Java data types 
    from an underlying input stream*/
    
    while ((thisLine = myInput.readLine()) != null)
    { //beginning of outer while loop 
    
    String[] result = thisLine.split(",");
         for (x=0; x<result.length; x++)
            {    
            	return result[x]; 
             }
    
    }  
    }  
    
      
     public static double [] strArray2DblArray(String [] strArray)
    {
      double [] dblArray = new double[strArray.length]; //create double Array with same sizas as the string array
      for (int i = 0; i<strArray.length;i++)
         {
          dblArray[i] = Double.parseDouble(strArray[i]);
         }
     return dblArray;
    }
      	
       	
     public static void zero (double numtozero[])
     {   int y=0;
     	double allzero[] = new double[numtozero.length];
         for (y=0; y<numtozero.length;y++)
         {
           allzero[y] = numtozero[y] * 0;
       System.out.println ("all zeroes" + allzero[y]);
     } 
     	
     	} 
    }
    It shows following error:-

    C:\Users\Jaimin\Documents\JCreator Pro\MyProjects\finalcode2.java:55: incompatible types
    found : java.lang.String
    required: java.lang.String[]
    return result[x];

    I don't know why this error is shown because in the readfile method, I have already created return datatype of string[].

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You don't want to do this:
    Java Code:
      String[] result = thisLine.split(",");
      for (x=0; x<result.length; x++)
      {    
        return result[x]; 
      }
    }
    Once return is encountered the method will end and spit out the result. In other words this method will try to exit on the first and only running of this loop, when x == 0. It will never loop to x = 1, or 2, or above because a return has been encountered. Not only that, when you dereference an array like so:

    result[x] or
    result[0],

    this is a String not an array, and so the compiler's error is correct: you are trying to return a String here, not an array.

    Please don't take this wrong, but I strongly advise you to go through the basic Java tutorials or a decent text book. You have much to learn before you do something as advanced as you're trying to do.

    Edit: my guess is that each line in the file that is read into the result array is one logical collection of data points. I further guess that you'll want to analyze each of these logical collection of data points. If so, then you'll want to create a new class to hold the data found in each result array, and place each object of this class created in your for loop into an ArrayList. Then once the input file has been completely read and the arraylist completely filled with data, you'd want to return this arraylist.

    For instance assume that the class to hold each datapoint is called SoilData, then
    Java Code:
    public ArrayList<SoilData> fileRead(.....)
    {
      String thisLine = "";
      ArrayList<SoilData> soilDataList = new ArrayList<SoilData>();
      while ((thisLine = myInput.readLine()) != null)
      {
        String[] result = thisLine.split(",");
        double rainfall = Double.parseDouble(result[0].trim());
        double soilFooContent = Double.parseDouble(result[1].trim());
        double soilBazContent = Double.parseDouble(result[2].trim());
        // ... etc
        SoilData soilDataPoint = new SoilData(rainfall, soilFooContent, soilBazContent,.... );
        soilDataList.add(soilDataPoint);
      }
    return soilDataList;
    }
    note: code not tested and is just for "for instance" purposes
    Last edited by Fubarable; 02-17-2009 at 01:12 AM.

  14. #14
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    k...
    well i knw i hav to learn a lot....bt my way of learning is different...unlike others. I have already started learning from couple of good books, but if I go on learning like that, I would just end up doing theory only. So, I wanna hav some practical hands on also.
    Dont take it wrong way, but I would like to learn Java in this manner only. I did learn Java before 2 years, but was totally theoretical based as I didn't practice much. So, I dont wanna repeat that because once I start learning, I would just go on studying theory and not doing any practice.

    So, pls try to help me out as right now I dont have enough time also to go back. Because for me, I have to only deal with these applications in java, I dont require to go into much detail even at a later stage.

    And, in last couple of weeks I have learnt Java so much in depth as compared to what I did in 2 months (before 2 years). I enjoy learning this way.

    So, pls help me out

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    We can only suggest, we can't write it for you. But realize that trying to learn Java by trial-and-error will be frustrating for you and for us. It just doesn't work. You need to do both practical trials like you're trying above, and study of what you call theoretical. Without the latter you are doomed to fail. Shoot you won't even be able to understand what we suggest. It's up to you.

    also note changes to my post above.

  16. #16
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default Help from the forum ...

    Just like Fubarable states, the forum does it's best to help people with their questions and doubts. Most of the time, complete solutions will not be supplied, but in it's place pseudo code, links, code snippets and suggestions may be provided. Use these wisely.
    Now, if one of the regulars in the forum indicates that you should study something first, then please pay attention. This advise is not given lightly. It comes from experience.
    Throwing code together on what you think should work (because you don't know) and not debugging it (because you don't understand it) will tire the forum very fast and the only answer you will get is "go study".

    For your last error (besides what Fubarable already said), you are trying to return in int array when the method is expected to return a string array.

    So.. please study methods and arrays

    Just some thoughts to try to help you...

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  17. #17
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    well thanks for your suggestions. I have started learning methods and arrays and found out lots of useful stuff which I was unaware earlier.

    Now I have made the following modifications in my code: instead of creating a separate method for parsing the string to double, I have made that as an integral part of the file read method.
    The code looks like:

    Java Code:
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.*;
    
    
    public class finalcode2 
    
    {  
    
    public static void main (String[] args) throws IOException   
    {  
        
        double output[] = fileread("data2.csv");
        System.out.println("values read from file"+ output);
        /*double orig_values[] = strArray2DblArray (output);*/
       /*system.out.println ("original values" +orig_values[]);*/
       zero (output); 
          }
    
    
       public static double[] fileread(String fName) throws IOException  
    {
    
    String thisLine; //string variable to take each record at a time
    
    int count=0; 
    int x=0;
    
    
    
    
    FileInputStream fis = new FileInputStream(fName); 
    //A FileInputStream obtains input from a file 
    
    DataInputStream myInput = new DataInputStream(fis);
    /*data input stream lets an application read primitive Java data types 
    from an underlying input stream*/
    
    while ((thisLine = myInput.readLine()) != null)
    { //beginning of outer while loop 
    
    String[] result = thisLine.split(",");
    double dblArray[] = new double[result.length];
         for (x=0; x<result.length; x++)
         	
            {    	/*return result[x];*/ 
            	dblArray[x] = Double.parseDouble(result[x]);
            		
            		
             }
    return dblArray; 
    } 
    
    }  
    
      
    /* public static double [] strArray2DblArray(String [] strArray)
    {
      double [] dblArray = new double[strArray.length]; //create double Array with same sizas as the string array
      for (int i = 0; i<strArray.length;i++)
         {
          dblArray[i] = Double.parseDouble(strArray[i]);
         }
     return dblArray;
    }*/
      	
       	
     public static void zero (double numtozero[])
     {   int y=0;
     	double allzero[] = new double[numtozero.length];
         for (y=0; y<numtozero.length;y++)
         {
           allzero[y] = numtozero[y] * 0;
       System.out.println ("all zeroes" + allzero[y]);
     } 
     	
     	} 
    }
    But, this shows following error:
    C:\Users\Jaimin\Documents\JCreator Pro\MyProjects\finalcode2.java:66: missing return statement }

    I know this might be a simple error, but I think I could learn only in this manner - by reading some theory and then practicing on this code.
    Pls help me out.

  18. #18
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default

    try to understand the errors... what is the following saying?
    C:\Users\Jaimin\Documents\JCreator Pro\MyProjects\finalcode2.java:66: missing return statement }
    What is on line 66 of your code? Do you have a return statement? If yes, is it in the right place? Look at the follwing code and see if the return statements is correctly placed? The return statement should be the last statement in the method.
    Java Code:
    .
    .
    .
    while ((thisLine = myInput.readLine()) != null)
    { //beginning of outer while loop 
    
    String[] result = thisLine.split(",");
    double dblArray[] = new double[result.length];
         for (x=0; x<result.length; x++)
         	
            {    	/*return result[x];*/ 
            	dblArray[x] = Double.parseDouble(result[x]);	
             }
    [B][COLOR="Red"]return dblArray;[/COLOR][/B] 
    } 
    
    }
    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  19. #19
    jaiminparikh is offline Member
    Join Date
    Feb 2009
    Posts
    24
    Rep Power
    0

    Default

    isn't it the last statement in the method ??

  20. #20
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default

    No... if you notice the return statement is in the while loop:
    Java Code:
    .
    .
    .
    while ((thisLine = myInput.readLine()) != null)
    [B][COLOR="Blue"]{[/COLOR][/B] //beginning of outer while loop 
    
    String[] result = thisLine.split(",");
    double dblArray[] = new double[result.length];
         for (x=0; x<result.length; x++)
         	
            {    	/*return result[x];*/ 
            	dblArray[x] = Double.parseDouble(result[x]);	
             }
    [B][COLOR="Red"]return dblArray;[/COLOR][/B] 
    [B][COLOR="blue"]}[/COLOR][/B] 
    
    }
    The first time that the while loops it will find the return statement and exit the method.... therefore the while loop will only lopp only once!

    So where should the return statement go?

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

Page 1 of 2 12 LastLast

Similar Threads

  1. Combining Individual Sounds - Urgent
    By JDCAce in forum Advanced Java
    Replies: 4
    Last Post: 12-05-2008, 06:17 AM
  2. Replies: 1
    Last Post: 11-18-2008, 05:48 PM
  3. Help combining loops into 1 program.
    By kewlgeye in forum New To Java
    Replies: 5
    Last Post: 04-22-2008, 10:58 AM
  4. Hash table with separate chaining
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-12-2008, 09:42 PM
  5. Replies: 1
    Last Post: 08-07-2007, 06:26 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •