I am reading a .Csv file and am having problems trying to get the information I want, set up the way I want.

Here is where my problem comes in:

String[] info = beanInfo.split("," , 3);
for (String str : info) {
	ip = info[0];
        hostname = info[1];
        ping = info[2];

}

Basically I am wanting to set column 1 to my ip information, column 2 to my hostname information, and column 3 to my ping information.

Whenever I attempt to print out any of the following strings ip, hostname, or ping; it duplicates the information its printing out by 3.

So basically if I do:

System.out.pringln(ip);

It will print out:

192.168.0.0
192.168.0.0
192.168.0.0

Instead of just:

192.168.0.0

If I print str, then it prints the information off exactly the way I want it just not by the columns I want it to be recognized with. This is what it would look like if I print out str:

192.168.0.0
myHostname
2 m/s
192.168.0.1
myHostname2
2 m/s
192.168.0.2
myHostname3
1 m/s
and so on...

So did I misunderstand the point of the 'number of fields' portion after my delimiter when splitting the string?

Recommended Answers

All 7 Replies

where do you try to print ip etc. Is it inside the loop?

> it duplicates the information its printing out by 3

Because you print out the information in a loop. The solution here is pretty simple; split the string read from the file/stdin using the given delimiter. If the length of the resulting array is not equal to 3, it means that the input wasn't in the format required. If the array length is 3, print out the details using:

String[] arr = str.split(",");
// assert length of the array is exactly 3
System.out.println(arr[0] + ", " + arr[1] + " and " + arr[2]);

where do you try to print ip etc. Is it inside the loop?

Inside the quote it produces all the information, but duplicated by 3.

Outside the loop it produces only the last instance of what I want printed out.

> it duplicates the information its printing out by 3

Because you print out the information in a loop. The solution here is pretty simple; split the string read from the file/stdin using the given delimiter. If the length of the resulting array is not equal to 3, it means that the input wasn't in the format required. If the array length is 3, print out the details using:

String[] arr = str.split(",");
// assert length of the array is exactly 3
System.out.println(arr[0] + ", " + arr[1] + " and " + arr[2]);

The array length will always be 3 as I have set the program recording the information only to record 3 fields.

However, I went ahead and tried your example and it is still printing out duplicates of 3.

Also a side note, I want to keep my ip, hostname, and ping equal to each array column as I am not interested in printing these out (its just to test it to make sure it will properly do what I want it to do later) I have a viewobject that will be displaying each of those fields.

My ultimate assumption is that if it duplicates 3 times when I am just printing it out, then it will also duplicate my viewobjects displayed. Which would display 2 unnecessary versions. However if its not in the loop I could be completely wrong and not have any problems with the code.

Perhaps I missed doing something from each of your posts?

Post your latest copy of compilable code which exhibits the behavior you mention [i.e. duplicate printing] along with the relevant CSV file.

Alright here is the code at the most basic (i've removed some information but its not necessary for the code to function)

Also note that I have my BufferedReader set up elsewhere and it looks like this:

BufferedReader reader = new BufferedReader(new FileReader("C:\\results.csv"));

Here is the code I have as of now:

import location.ParseResult;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class MyParser {

    private String ip = "xx.xx.xx.xx";
    private String hostname = "host";
    private String ping = "m/s";
    
    public ParseResult[] parseResult(BufferedReader reader) throws FileNotFoundException, IOException {

        
        ParseResult[] out;
        ArrayList<ParseResult> ipHostsFound = new ArrayList();
        
        try {
            boolean bHeadersDone = false;
            while (reader.ready()) {
                String beanInfo = reader.readLine();
                if (!bHeadersDone) {
                    if (beanInfo.contains("Ping")) {
                        bHeadersDone = true;
                    }
                } 
                else {
                    String[] values = beanInfo.split("," , 3);
                    for (String str : values) {
                        ip = values[0];
                        hostname = values[1];
                        ping = values[2]; 


                        if (ping.equals("[n/a]") || hostname.equals("[n/a]") ) {
                            //ignore this as I haven't implemented it yet
                        }
                        else {
			    //ignore this for now as I haven't implemented it

                        }


                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        out = (ParseResult[])ipHostsFound.toArray(new ParseResult[ipHostsFound.size()]);    // compiles without errors/exceptions but doesn't function as it should 
        return out;
        
    }

    /**
     * 
     * @return hostname of the parsed machine
     */
    public String getHostname() {
        return hostname;
    }

    /**
     * 
     * @return ipaddress of the parsed machine
     */
    public String getIP() {
        return ip;
    }
}

And I can't post the results.csv file as it has information that I don't want exposed. So for now, lets say the file looks like this:

IP,Hostname,Ping
192.168.0.1,myHostname1,0 ms
192.168.0.2,myHostname1,1 ms
192.168.0.3,myHostname1,1 ms
192.168.0.4,myHostname1,2 ms
192.168.0.5,myHostname1,1 ms
192.168.0.6,myHostname1,0 ms
192.168.0.7,myHostname1,[n/a]
192.168.0.8,myHostname1,1 ms 
192.168.0.9,myHostname1,0 ms
192.168.0.10,myHostname1,0 ms
192.168.0.11,myHostname1,0 ms
192.168.0.12,myHostname1,0 ms
192.168.0.13,myHostname1,[n/a]
192.168.0.14,myHostname1,1 ms

If needed as a csv file, its as simple as copying and pasting that info into notepad and saving it as results.csv

Now to show you what I was saying when I add the print statement in my loop I'll just add it in the snippet so you aren't confused as to where I put it.

else {
                    String[] values = beanInfo.split("," , 3);
                    for (String str : values) {
                        ip = values[0];
                        hostname = values[1];
                        ping = values[2]; 
                        
                        System.out.println(ip);
                        if (ping.equals("[n/a]") || hostname.equals("[n/a]") ) {
                            //System.out.println("Don't add this one!");
                            //Ignore, do not add to the mvl array
                        }
                        else {
                            //System.out.println("add this one!");
                            //add line to the results.csv
                            // not really needed, but will leave here till the if is complete
                        }


                    }
                }

Which then prints out:

192.168.0.1
192.168.0.1
192.168.0.1
192.168.0.2
192.168.0.2
192.168.0.2
192.168.0.3
192.168.0.3
192.168.0.3
192.168.0.4
192.168.0.4
192.168.0.4
etc...

If I put it out of the loop:

else {
                    String[] values = beanInfo.split("," , 3);
                    for (String str : values) {
                        ip = values[0];
                        hostname = values[1];
                        ping = values[2]; 
                        
                        if (ping.equals("[n/a]") || hostname.equals("[n/a]") ) {
                            //System.out.println("Don't add this one!");
                            //Ignore, do not add to the mvl array
                        }
                        else {
                            //System.out.println("add this one!");
                            //add line to the results.csv
                            // not really needed, but will leave here till the if is complete
                        }


                    }
                }
            }
            System.out.println(ip);

        } catch (Exception e) {
            e.printStackTrace();
        }

It only prints the last one:

192.168.0.14

Like I had previously mentioned, there is no need to loop over the result of the split method call. The split method returns an array whose elements are the host, ip addr and the ping.

Just remove the "for (String str : values) {" part and you should be good to go. For future references, please make sure you post a compilable piece of code which can be easily copy-pasted and run without making the poster jump through hoops to get it working.

Aw I see what I did, when I had removed the "for (String str : values) like you mentioned the first time, I had placed my print statement outside of the loop.

Thank you for clearing that up bud, I appreciate your help.

As for the compatible pierce of code, I apologize for not posting the full part in the beginning. Many forums ask that you not post the full thing as they don't want 300+ lines filling the page. While my code wasn't quite that long I figured it was along the same concept. But I'll keep that in mind when posting in the future.

Thanks again to both of you two for replying (~s.o.s~ and JamesCherrill)


(im going to remove the source in my post above as its not necessary to keep up there and its only taking up space)

*Edit*
Seems it won't allow me to edit that previous post for some reason :s

commented: BTW, welcome to Daniweb. Feel free to introduce yourself in the community introductions in case you haven't done so. :-) +28
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.