Page 1 of 2 12 LastLast
Results 1 to 20 of 27
  1. #1
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default Passing method as argument

    Hi all,

    I would like to modify a txt file (replace chars and delete) but I don't know how to use the return from a method into another method.

    This is the sample txt file

    Java Code:
    07/21/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    07/21/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    07/21/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    and this is the method to read this file, store and return a String variable name line

    Java Code:
    public String readTxtFile()throws IOException{
        String line="";
        try{
        FileReader fr = new FileReader("C:\\myfile.txt");
        BufferedReader br = new BufferedReader(fr);
    
       
        System.out.println("Contents in file:\n");
        while((line=br.readLine())!=null){
            System.out.println(line);
        }
        fr.close();
        br.close();
    
        }
        catch(FileNotFoundException fnf){
            System.out.println("File not found!");
    
    }
    return line;
    }
    What I have now is a string line that I want to convert using this method

    Java Code:
    public String conversion(){
    
    //String prova =("C:\\myfile.txt");
    String result="";
    
    StringBuilder remove = new StringBuilder();
    result=(remove.delete(16, 40).toString());
    result=result.replace(',','.');
    result=result.replace(';',',');
    result= result.replace("09:03","0900");
        System.out.println(result);
            return result;
        }
    Both these methods are in a class named -Methods-

    Now my questions are:

    1) how can I do to get the line return from first method and pass into the conversion method?
    Should I pass it as argument such as

    StringBuilder remove = new StringBuilder(readTxtFile()); ?

    2)I want to call these method in Main class, name -ConvertMain-, and for this reason I create an object name test .

    Java Code:
    public static void main(String[] args) throws IOException {
    
            Methods test = new Methods();
            test.readTxtFile();
        }
    If a call the readTxtFile method it all works fine, but how to call the second method in main class?

    Thank you very much!

    Susie
    Last edited by susieferrari; 06-09-2011 at 11:04 AM. Reason: type error

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    You can do it in two steps or one:

    Java Code:
    public static void main(String[] args) throws IOException {
        Methods test = new Methods();
        String str = test.readTxtFile();
        test.conversion(str);
        // or just
        // test.conversion(test.readTxtFile());
    }
    An alternative is to write another method in the Methods class that reads the file, converts the string and returns the contents.

  3. #3
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,928
    Rep Power
    19

    Default

    Java Code:
        while((line=br.readLine())!=null){
            System.out.println(line);
        }
    Out of curiosity, what is the point of this?
    Your line variable will always be null after this loop...

  4. #4
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    Thanks pbrockway2, what I do not know now is how to get String line returned from readTxtFile and pass it into conversion method.

    Regards,

    Susie

  5. #5
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    @Tolls: I add this print just to verify if my method works properly: if I get all lines printed then this method is good.

  6. #6
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,928
    Rep Power
    19

    Default

    But it's not good, because after that while loop your line variable will always (always) be null.
    So that method will always return null, unless the FNF exception is thrown, in which case it will return "".

  7. #7
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    Tolls, for what I know (but I may be wrong since I am a beginner) this statement say:

    Read what's in file until is different (!=) from null, and store in a string variable name line.

    If I ask to print line I get

    Java Code:
    run:
    Contents in file:
    
    07/21/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    07/22/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    07/23/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    BUILD SUCCESSFUL (total time: 0 seconds)
    and if I ask to print line.length() I get

    Java Code:
    Contents in file:
    
    69
    69
    69
    BUILD SUCCESSFUL (total time: 0 seconds)
    So I assume my string line is not null, or am I missing something?

    Regards,

    Susie

  8. #8
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,928
    Rep Power
    19

    Default

    Try doing println(line) and println(line.length) after the while loop (note, you'll get a null pointer exception on that one).
    All you're doing in that loop is reading each line and printing it out...you're not storing those lines anywhere.
    Each time back round the loop you are replcing the old line with the new one, until eventually you replace the old line with null.

  9. #9
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    Tolls you are right, thank you very much for your suggestion.

    Adding a println after while loop I get null

    Java Code:
    run:
    Contents in file:
    
    null
    BUILD SUCCESSFUL (total time: 0 seconds)
    so I must change this method and store each line in an array.

    Regards,

    Susie

  10. #10
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    OK I have modified the whole Methods class as:

    Java Code:
    package txtconvert;
    
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    
    public class Methods {
    
        public int numberOfLines()throws IOException{
        int nLines =0;
        try{
        FileReader flr = new FileReader("C:\\myfile.txt");
        BufferedReader bfr = new BufferedReader(flr);
    
        while((bfr.readLine())!=null){
            nLines++;}
    
        bfr.close();
        }
        catch(FileNotFoundException fnf){
            System.out.println("File not found "+ fnf.getMessage());
        }
    
        return nLines;
    }
    
        public String readTxtFile()throws IOException{
        
        String[]array=new String[numberOfLines()];
        try{
        FileReader fr = new FileReader("C:\\myfile.txt");
        BufferedReader br = new BufferedReader(fr);
    
    
       for(int i=0;i<array.length;i++){
                array[i]=br.readLine();
            }
          for(int i=0;i<array.length;i++){
        System.out.println(array[i]);
            }
        fr.close();
        br.close();
        }
    
        catch(FileNotFoundException fnf){
            System.out.println("File not found!");
    
    }
        return array.toString();
     }
    
    
    
        public String conversion() throws IOException{
    
    //String prova ="";
    String result=readTxtFile();
    
    StringBuilder remove = new StringBuilder();
    result=(remove.delete(16, 40).toString());
    result=result.replace(',','.');
    result=result.replace(';',',');
    result= result.replace("09:03","0900");
        System.out.println(result);
            return result;
        }
    
        
    }
    I am now sure method readTxtFile hold string data from myfile.txt and it return a String array;

    how can I pass this string array to conversion method?

    This is my main class

    Java Code:
    public class ConvertMain {
    
       
        public static void main(String[] args) throws IOException {
    
            Methods test = new Methods();
            String str=test.readTxtFile();
            
        }
    
    }
    Regards,

    Susie

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You could also return a string by appending line to a string builder each step through the loop. At the end return the builders toString method.

    You can pass the return of one method by treating the method as the return type. Let's say you have two methods, method1 and method2, method1 returns a string, and method2 takes a string, the easiest thing to do would be
    Java Code:
    method2(method1());
    Last edited by sunde887; 06-10-2011 at 09:34 AM. Reason: Added '()' in the method in code tags as tolls pointed out below

  12. #12
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,928
    Rep Power
    19

    Default

    Quote Originally Posted by sunde887 View Post
    You could also return a string by appending line to a string builder each step through the loop. At the end return the builders toString method.

    You can pass the return of one method by treating the method as the return type. Let's say you have two methods, method1 and method2, method1 returns a string, and method2 takes a string, the easiest thing to do would be
    Java Code:
    method2(method1[B]()[/B]);
    Small fix...

  13. #13
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Oops, thanks for catching that!

  14. #14
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    I have modified conversion method as:

    Java Code:
    public String conversion() throws IOException{
    
    //String prova ="";
    String result=readTxtFile();
    for(int i=0;i<result.length();i++){
    StringBuilder remove = new StringBuilder();
    result=(remove.delete(16, 40).toString());
    result=result.replace(',','.');
    result=result.replace(';',',');
    result= result.replace("09:03","0900");
            }
        System.out.println(result);
            return result;
        }
    readTxtFile() method return a string and I am trying to pass this string into conversion method but I get errors

    Java Code:
    run:
    07/21/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException
    07/22/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
    07/23/2009;09:03;2009-07-21 09:03:00.000;6,10;6,135;6,075;6,095;16234
            at java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:702)
            at java.lang.StringBuilder.delete(StringBuilder.java:255)
            at txtconvert.Methods.conversion(Methods.java:64)
            at txtconvert.ConvertMain.main(ConvertMain.java:15)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)
    What's wrong with this method? Should I return a string array rather than a string from readTxtFile method? I can't understand how to...

    Thanks

    Susie

  15. #15
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    None available to help me?

  16. #16
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,928
    Rep Power
    19

    Default

    I (personally) think you're going about this in slightly the wrong way.
    Note, I have no idea how large this file you;re processing is likely to get, but I tend to avoid reading in an entire file when all my processing is going to be line-by-line.

    So...during the reading of the file, call the conversion method, and then write the converted file to wherever it is you want.
    Java Code:
    for (each line in the file) {
        convert the line.
        write the converted line to wherever.
    }

  17. #17
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    Thank you very much Tolls!

    Susie

  18. #18
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    Last question for final step: read and conversion methods is now working fine, I've modified as

    Java Code:
    public String readTxtFile()throws IOException{
        
        String[]array=new String[numberOfLines()];
        try{
        FileReader fr = new FileReader("C:\\myfile.txt");
        BufferedReader br = new BufferedReader(fr);
    String line="";
    while((line=br.readLine())!=null){
        
        StringBuilder prova = new StringBuilder(line);
        line=(prova.delete(16,40).toString());
        line=line.replace(',','.');
        line=line.replace(';',',');
        line=line.replace("09:03","0900");
        for(int i=0;i<array.length;i++){
            array[i]=line;
        }    
    }
        fr.close();
        br.close();    
            }
        catch(FileNotFoundException fnf){
            System.out.println("File not found!");
    }
        for(int i=0;i<array.length;i++){
        System.out.println(array[i]);
            }
        return array.toString();
    }
    It returns a String but I can modify to return a String [ ]

    Now I have a method to create a new txt file

    Java Code:
    public void createTxt(){
        File fl = new File("C:\\convertedFile.txt");
        try{
        if(!fl.exists()){
            fl.createNewFile();
            System.out.println("File created succesfully!\n");
        }
            else{
                System.out.println("File already exist\n");
            }
            }
        catch(IOException e){
            System.out.println("Error!");
        }
        }
    on this new txt file I would like to write what's returned from readTxtFile, so the converted data. I have this method

    Java Code:
    public void writeTxtFile(){
    
        try{
            FileWriter fw = new FileWriter("C:\\convertedFile.txt",true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(readTxtFile());
        bw.close();
    
        System.out.println("Writing completed");
        }
        catch(Exception e){
            System.out.println("Error " +e.getMessage());
        }
    }
    I've passed readTxtFile method as argument into bw.write(), but it's not correct. Should I use a loop to write to txt file?

    Thanks all.

    Susie

  19. #19
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,928
    Rep Power
    19

    Default

    Why not simply write the converted line to the file as it's converted?
    Java Code:
    while((line=br.readLine())!=null){
        StringBuilder prova = new StringBuilder(line);
        line=(prova.delete(16,40).toString());
        line=line.replace(',','.');
        line=line.replace(';',',');
        line=line.replace("09:03","0900");
    
    // Write this line to the new file here.
    // This will mean opening the converted file before getting into the while loop.
    }

  20. #20
    Join Date
    Mar 2011
    Location
    Parma Italy
    Posts
    88
    Rep Power
    0

    Default

    Nice suggestion Tolls,

    no need to store data in array then loop again to write to a new txt file.

    Now the whole method (sum of readFile,convertFile and writeToFile) is

    Java Code:
    public String readTxtFile()throws IOException{
        
        String[]array=new String[numberOfLines()];
        try{
        FileReader fr = new FileReader("C:\\myfile.txt");
        BufferedReader br = new BufferedReader(fr);
    String line="";
    while((line=br.readLine())!=null){
        
        StringBuilder prova = new StringBuilder(line);
        line=(prova.delete(16,40).toString());
        line=line.replace(',','.');
        line=line.replace(';',',');
        line=line.replace("09:03","0900");
    //    for(int i=0;i<array.length;i++){
    //        array[i]=line;
    //    }
        FileWriter fw = new FileWriter("C:\\convertedFile.txt",true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(line);
        bw.close();
    }
        fr.close();
        br.close();    
            }
        catch(FileNotFoundException fnf){
            System.out.println("File not found!");
    }
    //    for(int i=0;i<array.length;i++){
    //    System.out.println(array[i]);
    //        }
        return array.toString();
    }
    It prints all lines in a txt file. But how to write row by row? I would like to have new line for each row, such as "\n" or System.out.println().

    Another question: writeToFile method needs a try catch block, do I need to use this block if I use the above method? I just have a try catch inside the readTxtFile method

    Thanks!

    Susie

Page 1 of 2 12 LastLast

Similar Threads

  1. perfect method parameter/argument match rejected. why?
    By collegestudent115 in forum Advanced Java
    Replies: 5
    Last Post: 10-31-2010, 06:55 PM
  2. Passing an array to a method.
    By twcast in forum New To Java
    Replies: 9
    Last Post: 02-10-2010, 09:13 AM
  3. Method as an argument?
    By StokedOnMe in forum New To Java
    Replies: 13
    Last Post: 09-18-2009, 06:29 AM
  4. Passing Class Reference to method
    By nekt in forum Advanced Java
    Replies: 5
    Last Post: 03-26-2009, 05:08 AM
  5. Replies: 4
    Last Post: 03-03-2009, 09:39 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
  •